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
:将值传递给变量时,必须在构造函数中指定对参数的引用。
输出: