简体   繁体   English

PHP:通过引用实例化类?

[英]PHP: Instantiate class by reference?

I'm converting some old PHP 4.x code for PHP 5.3. 我正在为PHP 5.3转换一些旧的PHP 4.x代码。 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. 在PHP4的Ye Olde Days中,=&在构造对象时是必需的。 In PHP 5, it's not. 在PHP 5中,它不是。

=& 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. 在PHP4中,默认情况下,对象是按值传递的,而不是通过引用传递的。 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. 在PHP5中,默认情况下通过引用传递对象。 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. 默认情况下,基元(或在PHP世界中经常调用的标量)仍然按值传递。

I find that when migrating OO PHP4 code to PHP5, quite a lot of & s get removed. 我发现,迁移OO PHP4的代码到PHP5的时候,相当多的&小号移除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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