当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

I'm trying to access a property of an object inside a method of that class. Here's what I have so far:

class Readout{

private $digits = array();

public function Readout($value) {

$length = strlen($value);

for ($n = 0; $n < $length; $n++) {

$digits[] = (int) $value[$n];

}

}

}

The goal is to be able to say $x = new Readout('12345'), where this creates a new Readout object with its $digits property set to the array [1,2,3,4,5].

I seem to recall there's some issue with scope in PHP, where $digits might not be visible inside Readout, so I tried replacing $digits[] = with $this->$digits[] =, but that gave me a syntax error.

网友答案:

the good syntax is:

$this->digits[]
网友答案:

The right syntax to access a class property inside a class method in your case is:

$this->digits[];

To create a new Readout object with 12345 set, you have to implement the class like this:

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');
网友答案:

That's because the correct way to call variables in a class varies based on whether you're accessing them as static or instanced (non-static) variables.

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
网友答案:

This works as well

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

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


     }
}

$obj = new Readout(12345);

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

?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: