传递对私有数组的引用

时间:2013-03-09 15:52:25

标签: php

我必须承认,所有关于PHP的“通过引用传递”的混淆已经影响了我,现在我不清楚了。我会想到以下代码:

class TestClass {

    private $my_precious = array ('one','two','three');

    public function &give_reference() {
        return $this->my_precious;
    }

}

$foobar = new TestClass();
$my_ref = $foobar->give_reference();
$my_ref = array ("four", "five", "six");

echo print_r($foobar,true);

会打印:

TestClass Object
(
    [my_precious:TestClass:private] => Array
        (
            [0] => four
            [1] => five
            [2] => six
        )

)

但是,唉,我的参考似乎没有持久力,而只是回声:

TestClass Object
(
    [my_precious:TestClass:private] => Array
        (
            [0] => one
            [1] => two
            [2] => three
        )

)

我该如何做到这一点?

2 个答案:

答案 0 :(得分:2)

您还必须通过引用分配:

$my_ref =& $foobar->give_reference();

答案 1 :(得分:0)

尝试:

class TestClass {

    private $my_precious = array ('one','two','three');

    public function & give_reference() {
        return $this->my_precious;
    }

}

$foobar = new TestClass();
$my_ref = & $foobar->give_reference();
$my_ref = array ("four", "five", "six");

echo print_r($foobar,true);