2014-04-30 5 views
1

PHP로 객체 지향 프로그래밍을 실험하고 있습니다. 다음 displayArray 함수를 실행하려고하면 해당 줄이 전혀 표시되지 않습니다. 아무도 내가 뭘 잘못하고 있는지 알아?객체 지향 프로그래밍을 사용하여 PHP에서 배열 표시

<?php 
class Student 
{ 
    var $name; 
    var $arr; 

    function Student() 
    { 
     $this->name = "bob"; 
     $this->addnametostring("Hello there "); 
     $this->arr = array(); 

     for($i=0; $i<30; $i++) { 
      $arr[$i] = rand(0,100); 
     } 
    } 

    function addnametostring($s) 
    { 
     $s.= " " . $this->name; 
     echo "$s <br>"; 
    } 

    function displayArray($amt) 
    { 
     foreach($this->arr as $key) { 
     //why is this not working 
     echo "<br>hello: ".$key; 
    } 
} 

}

$student = new Student; 
echo "<br>"; 
$student->displayArray(20); 

?> 
+1

@kevinabelita op 코드를 크게 변경하는 편집을 제안하지 마십시오. 서식을 편집하는 것은 좋지만 코드 자체를 변경하는 편집은 효과가 없습니다. [제안 된 편집] (http://stackoverflow.com/review/suggested-edits/4688940)은 op의 닫는 중괄호 중 하나를 제거했습니다. – computerfreaker

+1

닫는 중괄호를 잘 잡았습니다. 편집하는 동안 나는 그것을 놓쳤을 수 있습니다. 머리를 가져 주셔서 감사합니다. – user1978142

+0

화제에서, 그러나 당신은 OOPS 작풍은 php-4 작풍과 비슷합니다. 나는 var 대신 개인을 사용하도록 제안 할 것이다. 또한 PHP의 OOPS를 더 잘 이해하기 위해 public/protected/private과 함께 prefix 메소드를 사용한다. –

답변

3

변경이

for($i=0; $i<30; $i++){ 
    $arr[$i] = rand(0,100); 
} 

for($i=0; $i<30; $i++){ 
    $this->arr[$i] = rand(0,100); 
} 

편집

에 : 당신이 그렇게 전체 클래스가 같아야합니다, 생성자 누락 통지하지 않았나요 이

그래서 당신은 학생 함수를 호출하지 않는

function __construct(){ 
//some code 
} 

을 따를 16,

class Student(){ 

    var $name; 
    var $arr; 

    public function __construct() { 
     $this->name = "bob"; 
     $this->addnametostring("Hello there "); 
     $this->arr = array(); 

     for($i=0; $i<30; $i++){ 
      $this->arr[$i] = rand(0,100); 
     } 

    } 

    function addnametostring($s){ 
     $s.= " " . $this->name; 
     echo "$s <br>"; 
    } 

    function displayArray($amt){ 
     foreach($this->arr as $key){ 
      //why is this not working 
      echo "<br>hello: ".$key; 
     } 
    } 
} 
1

PHP에서 constructer입니다.

+0

그의 생성자 예제는 PHP에서 유효합니다. PHP는 __construct 및 메서드를 생성자로 허용합니다. 네임 스페이스 클래스 (5.3.3 이상)만이 __construct 만 생성자로 취급합니다. –

관련 문제