7

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?

jlb
  • 19,090
  • 8
  • 34
  • 65
  • 1
    yes that's a relic, all object are passed by reference in PHP 5. – RageZ Oct 25 '11 at 13:02
  • possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon Oct 25 '11 at 13:03

2 Answers2

3

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.

Marcus
  • 12,296
  • 5
  • 48
  • 66
  • Thanks @marcus. A followup, before php 5, what would be a use-case of assigning a variable to a NEW object by reference? Something to do with overwriting the variable's old value? – jlb Oct 25 '11 at 13:06
  • Here's and old article explaining it: http://nefariousdesigns.co.uk/archive/2006/08/object-oriented-php-part-2-relationships/. Look under the title "References" – Marcus Oct 25 '11 at 13:17
3

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.

millimoose
  • 39,073
  • 9
  • 82
  • 134
  • Thanks @Inerdia -- could you provide an example of "cloning it explicitly"? – jlb Oct 25 '11 at 13:23
  • @jib You clone an object explicitly using the [`clone` keyword](http://sk.php.net/manual/en/language.oop5.cloning.php) – millimoose Oct 25 '11 at 13:27
  • Ah, so this is in no relation to '&new'? You were simply referring to how many copies of an object instance exist, correct? – jlb Oct 26 '11 at 07:40