看起来在PHP中对象是通过引用传递的。即使赋值运算符似乎也没有创建对象的副本。
这里有一个简单而人为的证明:
<?php
class A {
public $b;
}
function set_b($obj) { $obj->b = "after"; }
$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.
set_b($a);
print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'
?>
无论是打印情况1还是情况2,我都获得了“after”。
那么,如何将$a按值而不是按引用传递给set_b()?
(object) ((array) $objectA)
可能会以更好的性能给您相同的期望结果,而不是使用clone $objectA
或new stdClass
。 - Binyamin