可变参考范围

class A {
  public $o;
  function __construct(&$o) {
    $this->o = $o;
  }
  function set($v) {
    $this->o["foo"] = $v;
  }
}

$o = ["hello" => "world"];
$a = new A($o);
$a->set(1);

echo json_encode($a->o)  // { "hello": "world", "foo": 1 }
echo json_encode($o)  // { "hello": "world" }

我必须怎么做才能使输出#2像输出#1一样?

评论
我幻成殇
我幻成殇

Using reference argument is not enough. You need to set your $this->o to an actual reference to $o:

$this->o = &$o;
点赞
评论
下载中....
下载中....

将值传递给变量时,必须在构造函数中指定对参数的引用。

function __construct(&$o) {
  $this->o = &$o;
}

输出:

echo json_encode($a->o);  // { "hello": "world", "foo": 1 }
echo json_encode($o);  // { "hello": "world", "foo":1 }
点赞
评论