2012-03-02 29 views
0

我試圖訪問該類的方法內的對象的屬性。這是我到目前爲止有:訪問該類的方法內的對象的屬性

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

我們的目標是能夠說$x = new Readout('12345'),在此創建了其$digits屬性設置爲數組[1,2,3,4,5]Readout對象。

我似乎記得有一些問題在PHP中,其中$digits可能無法看到裏面Readout範圍,所以我試着用$this->$digits[] =更換$digits[] =,但是這給了我一個語法錯誤。

+0

正在使用的是何種版本的PHP?因爲使用PHP5 +,您應該真正將構造函數指定爲'__construct($ value)'而不是類的名稱。另外從手冊中:*「從PHP 5.3.3開始,與名稱空間類名的最後一個元素具有相同名稱的方法將不再被視爲構造函數,這種更改不會影響非名稱空間類。」* – rdlowrey 2012-03-02 19:16:08

回答

2

良好的語法是:

$this->digits[] 
+0

這與不正確的'$ this - > $ digits []'是不一樣的,未來的讀者... – Joe 2012-03-02 19:21:14

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

這是因爲正確的方法來調用變量我ñ類根據您是以靜態還是實例(非靜態)變量訪問它們而有所不同。

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 2012-03-02 19:16:58

0

該作品,以及

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

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


    } 
} 

$obj = new Readout(12345); 

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

?>