Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of an ampersand '&' before the 'new' keyword?

Tags:

oop

php

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?

like image 357
jlb Avatar asked Oct 25 '11 12:10

jlb


2 Answers

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.

like image 67
millimoose Avatar answered Oct 28 '22 15:10

millimoose


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.

like image 30
Marcus Avatar answered Oct 28 '22 15:10

Marcus