2012-03-02 3 views
0

해당 클래스의 메서드 내에서 개체의 속성에 액세스하려고합니다. 여기에 지금까지이 작업은 다음과 같습니다해당 클래스의 메서드 내에서 개체의 속성에 액세스

class Readout{ 
    private $digits = array(); 
    public function Readout($value) { 
     $length = strlen($value); 
     for ($n = 0; $n < $length; $n++) { 
      $digits[] = (int) $value[$n]; 
     } 
    } 
} 

목표는이 배열 [1,2,3,4,5]로 설정된 $digits 속성 새로운 Readout 객체를 생성 $x = new Readout('12345')을 말할 수있을 것입니다.

나는 $digitsReadout 내부에 표시되지 않을 수 PHP에서 범위를 몇 가지 문제가있다 기억하는 것, 그래서 나는 $this->$digits[] =$digits[] =를 교체했지만, 그 날 구문 오류를 주었다.

+0

작업중인 PHP 버전은 무엇 일? 왜냐하면 PHP5 +에서는 생성자를 클래스 이름이 아닌'__construct ($ value)'로 지정해야하기 때문입니다. 또한 매뉴얼에서 : * "PHP 5.3.3부터 네임 스페이스가있는 클래스 이름의 마지막 요소와 같은 이름의 메서드는 더 이상 생성자로 취급되지 않습니다.이 변경은 비 네임 스페이스 클래스에는 영향을 미치지 않습니다. * – rdlowrey

답변

2

좋은 구문은 다음과 같습니다

$this->digits[] 
+0

미래의 독자들에게 부정확 한'$ this-> $ digits []'와 같지 않습니다 ... – Joe

0

귀하의 경우 클래스 메소드 내에서 클래스 속성에 액세스 할 수있는 권한 구문은 다음과 같습니다

$this->digits[]; 

가 12345 세트 새로운 판독 객체를 만들려면 다음과 같이 클래스를 구현해야합니다.

class Readout { 
    private $digits = array(); 

    public function __construct($value) 
    { 
     $length = strlen($value); 
     for ($n = 0; $n < $length; $n++) { 
      $this->digits[] = (int) $value[$n]; 
     } 
    } 
} 

$x = new Readout('12345'); 
0

올바른 방법은 변수 i를 호출하기 때문입니다. 클래스는 정적 또는 인스턴스 (비 정적) 변수로 액세스하는지 여부에 따라 다릅니다.

class Readout{ 
    private $digits = array(); 
    ... 
} 

$this->digits; //read/write this attribute from within the class 

class Readout{ 
    private static $digits = array(); 
    ... 
} 

self::$digits; //read/write this attribute from within the class 
+0

간단히 말해, 새로운 인덱스를 설정하는 올바른 방법은 다음과 같습니다 : $ this-> digits [] = '값'; 당신이 그것을 사용하는 맥락에서. – Brian

0

이뿐만 아니라

<?php 
class Readout{ 
    public $digits = array(); 
    public function Readout($value) { 

     $this->digits = implode(',',str_split($value)); 


    } 
} 

$obj = new Readout(12345); 

echo '['.$obj->digits.']'; 

?> 
관련 문제