我真的很难说出我期望做什么,所以我将显示代码和预期的输出。
class A {
public $someProp = null;
}
class B {
function run() {
$args = func_get_args();
call_user_func_array(array($this, 'someOtherFunction'), $args);
}
function someFunction($object) {
$object->someProp = 'Some Value';
}
function someOtherFunction(&$object) {
$a = new A();
$this->someFunction($a);
// Expected
var_dump($a->someProp); // Some Value
// PROBLEM LIES HERE
// I am trying to set the referenced original object to the altered new object
// I'm guessing this line breaks the original reference, so how can I avoid that?
$object = $a;
}
}
$a = new A();
// Expected
var_dump($a->someProp); // null
$b = new B();
$b->someFunction($a);
// Expected
var_dump($a->someProp); // Some Value
$a = new A();
$b->run($a);
// Unexpected, expecting 'Some Value'
var_dump($a->someProp); // null
编辑好的,我编辑了对someOtherFunction的调用,以更好地反映我的实时代码。它是使用call_user_func_array调用的,它会给出这个错误。
警告:B::someOtherFunction()的参数1预计是一个引用,值给定
通过引用传递参数:
function someOtherFunction(&$object) {
我对这个解决方案并不完全满意,但它在我的情况下工作。我理解这个解决方案可能会在受保护和私有属性的情况下导致问题。但我唯一的其他选择是为一个参考问题重新编写整个框架。
function someOtherFunction($object) {
$a = new A();
$this->someFunction($a);
// Expected
var_dump($a->someProp); // Some Value
// PROBLEM LIES HERE
// I am trying to set the referenced original object to the altered new object
// I'm guessing this line breaks the original reference, so how can I avoid that?
//$object = clone $a;
// Copy each property manually
foreach(get_object_vars($a) as $key => $value) {
$object->$key = $value;
}
}