开发者

Using & to get object's reference in PHP is redundant?

开发者 https://www.devze.com 2023-01-31 04:16 出处:网络
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:

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开发者_如何学Python 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?


In php5, yes, it is redundant and pointless.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消