简体   繁体   中英

PHP: Instantiate class by reference?

I'm converting some old PHP 4.x code for PHP 5.3. I've come across the following, and I'm not sure what it does.

$variable =& new ClassName();

What is the difference between that, and:

$variable = new ClassName();

In Ye Olde Days of PHP4, =& was necessary when constructing objects. In PHP 5, it's not.

=& does reference assignment.

EG:

$a = 'a';
$b =& $a;
$b = 'b';
echo $a; // Prints 'b', since a and b have been linked by &=.

In other words, it has its uses, just not when instantiating an object. For that use, it's been depreacted.

In PHP4, objects were passed by value by default, rather than by reference. This means that a copy of the object was made upon assignment. If you wanted to pass the object by reference instead of by value, you could use the & operator. In PHP5, objects are passed by reference by default. So the & is no longer necessary when dealing with objects. Primitives (or scalars as they are often called in the PHP world) are still passed by value by default.

I find that when migrating OO PHP4 code to PHP5, quite a lot of & s get removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM