'&' 的意义是什么?在“新”之前关键词?
你为什么要这样做?
$a = &new <someclass>();
例如,SimpleTest 的 SimpleBrowser 的文档使用此语法 (http://www.simpletest.org/en /browser_documentation.html)。
$browser = &new SimpleBrowser();
这有什么用吗?这是 PHP 4 的遗物吗?
编辑:
我知道&符号通过引用返回,但是通过引用返回对象的新实例有什么意义?
Why would you do this?
$a = &new <someclass>();
For example, the documentation for SimpleTest's SimpleBrowser uses this syntax (http://www.simpletest.org/en/browser_documentation.html).
$browser = &new SimpleBrowser();
Is there any use to this? Is this a relic of PHP 4?
Edit:
I understand that the ampersand returns by reference, but what is the point of returning a NEW instance of an object by reference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 PHP5 中,对象使用不透明对象句柄传递。您仍然可以引用持有此类句柄的变量并为其赋予另一个值;这就是 PHP5 中
&new
构造的作用。但它似乎并不是特别有用 - 除非您显式克隆它,否则特定对象实例只有一份副本,并且如果您愿意,您可以在实例化后随时引用它的句柄。所以我的猜测是,您发现的代码是&new
成为必要模式时的保留。In PHP5, objects are passed using opaque object handles. You can still make a reference to a variable holding such a handle and give it another value; this is what the
&new
construct does in PHP5. It doesn't seem to be particularly useful though – unless you clone it explicitly, there's only ever one copy of a particular object instance, and you can make references to handles to it anytime after instantiation if you want to. So my guess would be the code you found is a holdover from when&new
was a necessary pattern.自 PHP5
new
自动返回引用。因此,在这种情况下使用=&
是没有意义的(如果我没有错误地给出 E_STRICT 消息的话)。在 PHP5 之前,使用
=&
是为了获取对象的引用。如果您将对象初始化为变量,然后将其分配给新变量,则这两个变量都对同一个对象进行操作,就像今天在 PHP5 中一样。Since PHP5
new
returns references automatically. Using=&
is thus meaningless in this context (and if I'm not mistaken giving a E_STRICT message).Pre-PHP5 the use of
=&
was to get a reference to the object. If you initialized the object into a variable and then assigned that to a new variable both of the variables operated on the same object, exactly like it is today in PHP5.