访问该类的方法内部的对象的属性


Access a property of an object inside a method of that class

我正在尝试访问该类的方法中的对象的属性。到目前为止,我拥有的是:

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'),其中这将创建一个新的Readout对象,其$digits属性设置为数组[1,2,3,4,5]

我似乎记得PHP中的scope有一些问题,其中$digitsReadout中可能不可见,所以我尝试用$this->$digits[] =替换$digits[] =,但这给了我一个语法错误。

好的语法是:

$this->digits[]

在您的情况下,访问类方法内部的类属性的正确语法是:

$this->digits[];

要创建一个设置了12345的新Readout对象,您必须实现这样的类:

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');

这是因为调用类中变量的正确方式因您是将它们作为静态变量还是实例化(非静态)变量访问而有所不同。

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

这也适用

<?php
class Readout{
    public $digits = array();
    public function Readout($value) {
        $this->digits = implode(',',str_split($value));

     }
}
$obj = new Readout(12345);
echo '['.$obj->digits.']';
?>