php参考 [英] Php By Reference
问题描述
有人可以解释一下&"是什么吗?执行以下操作:
Can someone please explain what the "&" does in the following:
class TEST {
}
$abc =& new TEST();
我知道这是参考.但是有人可以说明为什么以及何时需要这种东西吗?或将我指向一个网址,其中的解释很好.我无法理解这个概念.
I know it is by reference. But can someone illustrate why and when I would need such a thing? Or point me to a url where this is explained well. I am unable to grasp the concept.
非常感谢您.
推荐答案
据我了解,您并不是在问一般的PHP引用,而是关于$foo =& new Bar();
构造习惯的问题.
As I understand it, you're not asking about PHP references in general, but about the $foo =& new Bar();
construction idiom.
这仅在PHP4中可见,因为通常的$foo = new Bar()
存储对象的副本.除非类在构造函数中存储了对$ this的引用,否则通常不会注意到这一点.稍后在对返回的对象调用方法时,当意图可能只有一个时,将存在该对象的两个不同副本.
This is only seen in PHP4 as the usual $foo = new Bar()
stores a copy of the object. This generally goes unnoticed unless the class stored a reference to $this in the constructor. When calling a method on the returned object later on, there would be two distinct copies of the object in existence when the intention was probably to have just one.
考虑以下代码,其中构造函数在全局var中存储对$ this的引用
Consider this code where the constructor stores a reference to $this in a global var
class Bar {
function Bar(){
$GLOBALS['copy']=&$this;
$this->str="hello";
}
}
//store copy of constructed object
$x=new Bar;
$x->str="goodbye";
echo $copy->str."\n"; //hello
echo $x->str."\n"; //goodbye
//store reference to constructed object
$x=&new Bar;
$x->str="au revoir";
echo $copy->str."\n"; //au revoir
echo $x->str."\n"; //au revoir
在第一个示例中,$ x和$ copy引用了Foo的不同实例,但是在第二个示例中,它们是相同的.
In the first example, $x and $copy refer to different instances of Foo, but in the second they are the same.
这篇关于php参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!