Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

&new MyClass() vs new MyClass() in PHP

Tags:

php

Is there any difference between the following?

$myVar=&new MyClass();
$myVar=new MyClass();

I am coding in PHP

like image 643
Casebash Avatar asked Nov 22 '11 01:11

Casebash


2 Answers

If using PHP5, there is no difference.

If using PHP4, the former passes a reference to the new object.

This is because "new" does not return a reference by default, instead it returns a copy.

Source.

Give this a read, too.

like image 148
alex Avatar answered Oct 15 '22 23:10

alex


Using PHP5? Then you should use the following:

$myVar=new MyClass();

This is the accepted way to initialize a class.


Using the following when E_STRICT is enabled:

$myVar=&new MyClass();

will cause the PHP runtimes to raise the warning Deprecated: Assigning the return value of new by reference is deprecated.

like image 24
Andrew Moore Avatar answered Oct 15 '22 23:10

Andrew Moore