PHP 中的全局变量、对象和引用 - 它们如何工作?
我知道通过使用“=”对象是通过引用分配的,对于其他变量以及字符串和整数等数据类型,您需要使用“=&”通过引用分配。当您使用“=&”显式地通过引用分配对象时,它似乎不会影响分配。但是,当您将对象分配给全局时,它就会这样做。
请考虑以下事项:
<?php
$global_obj = null;
class my_class {
var $value;
public function __construct() {
global $global_obj;
$global_obj =& $this;
$GLOBALS['some_var'] = $this;
}
}
$a = new my_class();
$a->my_value = 5;
$global_obj->my_value = 10;
echo 'A: ' . $a->my_value; //5
echo '<br />';
echo 'Global Object: ' . $global_obj->my_value; //10
echo '<br />';
echo 'Globals Array Value: ' . $some_var->my_value; //5
?>
如果删除上面代码中的 & 符号,$this 将通过引用分配给 $global_obj。我的问题是为什么那里有&符号似乎可以阻止这种情况发生?
谢谢
I understand that by using "=" objects are assigned by reference and for other variable and for datatypes like strings and integers you need to use "=&" to assign by reference. When you assign an object by reference explicitly using "=&", it seems to not affect assignment. However when you assign the object to a global it does.
Consider the following:
<?php
$global_obj = null;
class my_class {
var $value;
public function __construct() {
global $global_obj;
$global_obj =& $this;
$GLOBALS['some_var'] = $this;
}
}
$a = new my_class();
$a->my_value = 5;
$global_obj->my_value = 10;
echo 'A: ' . $a->my_value; //5
echo '<br />';
echo 'Global Object: ' . $global_obj->my_value; //10
echo '<br />';
echo 'Globals Array Value: ' . $some_var->my_value; //5
?>
If you remove the ampersand in the code above $this is assigned to $global_obj by reference. My question is why does having the ampersand in there seemingly stop this from happening?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里发生的事情是
$global_obj
是对变量$this
的引用。$this
是一个伪变量,存在于方法内部,作为对当前对象的引用。但谁知道当$this
超出方法范围时会发生什么。引用$this
可能不是一个好主意。事实上,如果您进一步研究一下,在构造函数返回后,如果您检查
$global_obj
,它的值为null
。 PHP 引擎可能会在方法退出后将$this
设置为 null(但这没有在任何地方记录),以及您的$global_obj
,因为它是对变量 < code>$this,跟随它。当您在null
上设置属性时,它会自动实例化一个stdClass
类的新对象,因此看起来成功了。当然,这是一个与$a
中完全不同的对象。What is happening here is that
$global_obj
is a reference to the variable$this
.$this
is a pseudo-variable that exists inside methods to be a reference to the current object. But who knows what happens to$this
when it goes outside of the method scope. It is probably a bad idea to have a reference to$this
.In fact, if you investigate it a bit further, after your constructor returns, if you examine
$global_obj
, its value isnull
. The PHP engine probably sets$this
to null after the method exits (but this is not documented anywhere), and your$global_obj
, since it is a reference to the variable$this
, follows it. When you set an attribute onnull
, it instantiates a new object of classstdClass
automatically, so it seems to succeed. But of course this is a completely different object than the one in$a
.