向引用中添加数据以更改PHP中被引用的数组


Adding data to a reference to change the referenced array in PHP

我已经构建了一个函数来检索数组的最后一个指定键,它引用了数组并显示得很好,但是,当我尝试添加到引用变量时,它不会影响被引用的数组。

这是我的代码:

class test {
    public function __construct() {
        // For testing
        $this->keys[] = 'key1';
        $this->keys[] = 'key2';
        $this->array['key1']['key2'] = 'Hello World';
    }
    protected function &getArray() {
        $array = &$this->array;
        foreach($this->keys as $key) {
            $array = &$array[$key];
        }
        return $array;
    }
    function add() {
        $tmpArray = $this->getArray();
        print_r($tmpArray);
        echo "<br>'n";
        $tmpArray = 'Goodbye World';
        print_r($tmpArray);
        echo "<br>'n";
        print_r($this->array);
    }
}
$test = new test;
$test->add();

综上所述,add()和__construct()是用于测试的。我正在尝试使用add()添加到$this->array。但是,当我指定$tmpArray = 'Goodbye World'时,引用的数组$this->array['key1']['key2']仍然是Hello World。

有人能帮我指明正确的方向吗?

为了在PHP中返回引用,您需要使用&两次,一次在定义中,另一次在赋值中。你错过了任务中的一个:

$tmpArray = &$this->getArray();

有关详细信息,请参阅PHP:ReturningReferences,请不要问为什么,因为我无法生成PHP行为的基本原理。