使用 &在 PHP 中获取对象的引用是多余的吗?

发布于 2024-10-07 15:15:05 字数 649 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡淡の花香 2024-10-14 15:15:05

在 php5 中,是的,这是多余且毫无意义的。

In php5, yes, it is redundant and pointless.

尬尬 2024-10-14 15:15:05

据我所知,与引用相关的唯一已被弃用的是调用时传递引用(例如 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.

沉溺在你眼里的海 2024-10-14 15:15:05

此页面可能对您有帮助:
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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文