Page 1 of 1

What is the difference between new and &new

Posted: Wed Aug 09, 2006 2:56 pm
by ZeroFear
what is the difference between these two statements?

$object = new Object();

$object = &new Object();



Anyone? I have a few guesses but id like to be sure.

Posted: Wed Aug 09, 2006 3:00 pm
by RobertGonzalez
'&' references the object that you are creating, it doesn't actually use the object.

More on reference from PHP.net...

Re: What is the difference between new and &new

Posted: Wed Aug 09, 2006 4:01 pm
by bokehman
ZeroFear wrote:$object = &new Object();
That's not legal syntax under PHP 5.

Re: What is the difference between new and &new

Posted: Wed Aug 09, 2006 4:38 pm
by Christopher
The problem in PHP4 was that the "$obj = new MyClass();" allocated two object -- one was created by the "new" and the assignment made a copy. Assigning by reference did not make the copy so became common usage.
bokehman wrote:That's not legal syntax under PHP 5.
I believe the '&' is ignored and handles, not references, are used.

Re: What is the difference between new and &new

Posted: Wed Aug 09, 2006 4:59 pm
by bokehman
arborint wrote:I believe the '&' is ignored and handles, not references, are used.
It raises an E_STRICT.

Posted: Wed Aug 09, 2006 8:18 pm
by Ambush Commander
Doesn't seem to be the case for me...

Code: Select all

<?php

error_reporting(E_STRICT);

class A {}
$a =& new A;

?>
Running PHP 5.1.4. They did some weird stuff with E_STRICT though.

As for whether or not the reference is ignored, it's hard to say, because unless you have a variable, handles and references are identical.

Posted: Wed Aug 09, 2006 9:35 pm
by Jenk
E_STRICT is raised when you pass an object by reference, but not assign, because in php5 objects are always passed by reference.

Code: Select all

<?php

function & foo (&$obj)
{
    return $obj;
}

$obj =& foo(new stdClass);

?>
However, I think, like you say, they may have removed that particular E_STRICT message because it is/was such common practice.

Re: What is the difference between new and &new

Posted: Wed Aug 09, 2006 10:55 pm
by Christopher
bokehman wrote:It raises an E_STRICT.
Yes ... which can be helpful in identifying in identifying the problem when upgrading from PHP4 to PHP5. But I believe internally that they ignore attempts to assign an object by reference and just use handles -- they obviously identify the circumstance.