我正在尝试访问该类的方法中的一个对象的属性。这是我到目前为止所知道的:
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中的作用域有一些问题,在Readout中可能看不到$digits,所以我尝试用$this->$digits[] =替换$digits[] =,但这给了我一个语法错误。
发布于 2012-03-03 03:08:13
好的语法是:
$this->digits[]发布于 2012-03-03 03:12:35
在本例中,访问class方法中的class属性的正确语法是:
$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');发布于 2012-03-03 03:15:14
这是因为在类中调用变量的正确方式取决于您是将它们作为静态变量还是实例化(非静态)变量进行访问。
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 classhttps://stackoverflow.com/questions/9538937
复制相似问题