使用 &在 PHP 中获取对象的引用是多余的吗?
在 PHP 中,所有对象变量实际上都是指向对象的指针(不是?),该语言隐式处理这个问题(对吗?),但我看到许多 php 代码在参数中指定引用,如下所示:
function someMethod(SomeClass& $obj)
{
//...
}
我也看到过这样的事情:
function add()
{
$object = new SomeClass;
self::$objects[] =& $object;
}
如果我错了,请纠正我,但这里不会有任何区别:
self::$objects[] =& new SomeClass
self::$objects[] = new SomeClass
我是对的吗??????
我测试的另一件事:
class SomeClass{}
$obj =& new SomeClass; // is in fact deprecated, doesn't work
$obj = new SomeClass;
$obj2 =& $obj; // works, but should also be deprecated!! No?
In PHP, all object-variables are actually pointers to objects (no?), the language handles this implicitly (right?), yet I see many php code specifying references in parameters such as this:
function someMethod(SomeClass& $obj)
{
//...
}
I've also seen things like this:
function add()
{
$object = new SomeClass;
self::$objects[] =& $object;
}
Correct me if I'm wrong, but there wouldn't be any difference here:
self::$objects[] =& new SomeClass
self::$objects[] = new SomeClass
Am I right??????
Another thing I tested:
class SomeClass{}
$obj =& new SomeClass; // is in fact deprecated, doesn't work
$obj = new SomeClass;
$obj2 =& $obj; // works, but should also be deprecated!! No?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 php5 中,是的,这是多余且毫无意义的。
In php5, yes, it is redundant and pointless.
据我所知,与引用相关的唯一已被弃用的是调用时传递引用(例如
somefunction(&$var);
您的代码示例可能具有
& ;
符号用于 PHP 4 兼容性。无论您是否使用&
来处理 PHP 5 中的对象引用,都没有太大区别。当然有一个 略有不同(在 PHP 5 中按值传递引用与使用&
按引用传递对象之间),但在大多数情况下,在 PHP 5 中运行时它不会影响您的代码。The only thing related to references that is deprecated as far as I know is call-time pass-by-reference (e.g.
somefunction(&$var);
Your code samples likely have the
&
symbol for PHP 4 compatibility. It doesn't make much of a difference whether you use&
or not to work with object references in PHP 5. Granted there is a slight difference (between passing references by value in PHP 5, and using&
to pass objects by reference), but in most cases it shouldn't affect your code when run in PHP 5.此页面可能对您有帮助:
http://www.php.net/manual/en/language.operators .assignment.php
new
自动返回一个引用,因此您不再对新声明的对象使用= &
。This page may be helpful to you:
http://www.php.net/manual/en/language.operators.assignment.php
new
automatically returns a reference, so you don't use the= &
anymore with a newly declared object.