【发布时间】:2016-12-09 19:26:12
【问题描述】:
我看到一些与 PHP 中的引用/赋值相关的令人困惑的行为...
private function doSomething($things)
{
foreach ($things as $thing) {
echo $thing->property; // 'foobar'
$copyThing = $thing;
unset($copyThing->property);
echo $thing->property; // undefined
我希望在通过引用传递变量时会出现这种行为 (&$thing),但我不想在这里这样做,而且它似乎无论如何都会发生。我错过了什么?
【问题讨论】:
-
foreach 循环中的对象总是通过引用传递
-
$thing 已经是 $things 在 foreach 循环中的传递引用
-
@MM 哇!在任何最新版本的 PHP 中,该默认值是否发生了变化?我发誓我记得必须使用
&$var来公开通过引用。 -
如果它是一个对象,那么不是.... 因为持有对象的变量总是一个指针
-
你需要
clone你的对象,例如:foreach ($things as $thing) { $copyThing = clone $thing; unset($copyThing->property); }
标签: php pass-by-reference variable-assignment