如何在同一个PHP对象访问一个函数内的公共数组?数组返回NULL


How to access a public array inside a function in the same PHP object? Array returns NULL

我在对象中编写一个函数,需要访问创建对象时构造的数组。我可以使用$this->var访问函数内的正常变量,但我不能以同样的方式使用$this->array['key']访问数组。为什么我的函数不能使用数组?

下面是有问题的代码:

class User
{
    public $_x;
    public $_y;
    public $_z;
    public $_array;
    public function __construct($username)
    {
        $_x = 'a';
        $_y = 'b';
        $_z = 'c';
        $_array = array( 'red' => $_x,  'blue' => $_y,  'green' => $_z,);
    }
    public function myFunction()
    {
        echo $this->_x . "<br>";
        echo $this->_y . "<br>";
        echo $this->_z . "<br>";
        echo $this->_array['red'] . "<br>";
        echo $this->_array['blue'] . "<br>";
        echo $this->_array['green'] . "<br>";
        var_dump($this->_array);
    }
}
$user = new User;
$user->myFunction();

显示:

b

c

你忘了$this:

public function __construct($username)
{
    $_x = 'a';  // LOCAL variable, exists only in the constructor
    $this->_x = 'a'; // class variable
    ^^^^^----you forgot this

您也必须在构造函数中使用$this关键字:

public function __construct($username)
{
    $this->_x = 'a';
    $this->_y = 'b';
    $this->_z = 'c';
    $this->_array = array( 'red' => $this->_x,  'blue' => $this->_y,  'green' => $this->_z,);
}