为什么我的 PHP 对象是通过引用传递的 [英] Why are my PHP objects passed by reference
问题描述
我看到一些与 PHP 中的引用/赋值相关的令人困惑的行为...
私有函数 doSomething($things){foreach ($things as $thing) {echo $thing->property;//'foobar'$copyThing = $thing;未设置($copyThing-> 属性);echo $thing->property;//不明确的
我希望在通过引用传递变量时会出现这种行为 (&$thing
),但我并不打算在这里这样做,而且无论如何它似乎都在发生.我错过了什么?
只是解释我的评论:
<块引用>foreach 循环中的对象总是通过引用传递
当您对对象数组使用 foreach 循环时,您在循环内使用的变量是指向该对象的指针,因此它用作引用,循环内对象的任何更改都是对象的更改外部.这是因为:
<块引用>对象总是通过引用传递(@user3137702 引用)
详细的官方解释这里.
<小时>当您复制和取消设置变量时:
<块引用>$copyThing = $thing;未设置($copyThing-> 属性);
您正在创建另一个指针并取消设置它,因此原始值消失了.事实上,由于 foreach 循环也使用了一个指针,$things
数组也会受到影响.
检查这个 ideone(注意 vardump ['a' 属性消失的地方],因为输出是和你得到的一样)
<小时>我不知道它在哪个版本中改变了,如果有的话,因为它似乎是默认的对象/指针行为
<小时>作为一种解决方法(一些想法):
- 复制你的初始数组
- 使用克隆:
$x = clone($obj);
(只要默认的复制构造函数适用于您的对象)
I'm seeing some confusing behavior related to reference/assignment in PHP...
private function doSomething($things)
{
foreach ($things as $thing) {
echo $thing->property; // 'foobar'
$copyThing = $thing;
unset($copyThing->property);
echo $thing->property; // undefined
I expect this behavior when passing variables by reference (&$thing
) but I'm not trying to do that here and it seems to be happening anyway. What am I missing?
Just explaining my comment:
objects in foreach loops are always passed by reference
When you use a foreach loop for an array of objects the variable that you are using inside the loop is a pointer to that object so it works as a reference, any change on the object inside the loop is a change on the object outside. This is because:
objects are always passed by reference (@user3137702 quote)
Detailed and official explanation here.
When you copy and unset your variable:
$copyThing = $thing; unset($copyThing->property);
you are creating another pointer and unseting it, so the original value is a gone. As a matter of fact, since the foreach loop also uses a pointer the $things
array is also affected.
check this ideone (notice the vardump [where the 'a' property is gone], as the output is the same as you got)
I do not know in which version it changed, if ever, as it seems like default object/pointer behavior
As a workaround (some ideas):
- Copy your initial array
- Use clone:
$x = clone($obj);
(As long as the default copy constructor works for your objects)
这篇关于为什么我的 PHP 对象是通过引用传递的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!