2012-03-02 31 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.']'; 

?>