0

我必须承认,关于 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
        )

)

我怎样才能使这项工作?

4

2 回答 2

2

您还必须通过引用分配:

$my_ref =& $foobar->give_reference();
于 2013-03-09T16:00:42.697 回答
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);
于 2013-03-09T16:11:16.540 回答