变量引用范围

Variable reference scope

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 一样?

使用引用参数是不够的。您需要将 $this->o 设置为对 $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 }