如何通过引用传递两种方法?

时间:2013-03-14 09:51:40

标签: php oop reference

class foo {
    public $value1 = 1;

    public function setValue1(& $v) {
        $this->value1 = $v;
    }
}

class bar {
    public $value2 = 2;
    public $obj;

    public function & getValue2() {
        return $this->value2;
    }

    public function setValue2($v) {
        $this->value2 = $v;
}
}

$foo = new foo();
$bar = new bar();

$bar->obj = $foo;

$foo->setValue1($bar->getValue2()); //<-- not works

//$foo->value1 =& $bar->getValue2(); //<-- works

$bar->setValue2(4);


var_dump($foo, $bar) Prints:
    object(foo)[124]
      public 'value1' => int 2
    object(bar)[123]
      public 'value2' => int 4
      public 'obj' => 
        object(foo)[124]
          public 'value1' => int 2

为什么当我使用$ foo-&gt; setValue1($ bar-&gt; getValue2())时,foo-&gt; value1等于2而bar-&gt; value2等于4?

我正在尝试使用方法而不是属性来传递引用和引用返回。

2 个答案:

答案 0 :(得分:0)

这有效:

class foo {
    public $value1 = 1;

    public function &setValue1( $v ) { // <-- !
        $this->value1 = &$v; // <-- !
    }
}

class bar {
    public $value2 = 2;
    public $obj;

    public function &getValue2() {
        return $this->value2;
    }

    public function &setValue2( $v ) { // <-- !
        $this->value2 = $v;
}
}

$foo = new foo();
$bar = new bar();

$bar->obj = $foo;

$tmp =& $bar->getValue2(); // <-- !
$foo->setValue1( &$tmp ); // <-- !

$bar->setValue2( 4 );

echo "<pre>" . print_r( $foo, 1 ) . "</pre>";
echo "<pre>" . print_r( $bar, 1 ) . "</pre>";

输出:

foo Object
(
    [value1] => 4
)

bar Object
(
    [value2] => 4
    [obj] => foo Object
        (
            [value1] => 4
        )

)

答案 1 :(得分:0)

正确答案是方法内部的参考$ foo-&gt; value1 =&amp; $ v;