简体   繁体   中英

PHP class and objects

What is the difference between

$obj1 = new Test();
$obj2 = new $obj1;

and

$obj1 = new Test();
$obj2 = new Test();

Both are creating different memory location for objects. Does it have any difference...?

$obj2 = new $obj1;

use like this $obj2 = $obj1;

you have two variables refering to the same instance of Test.

but here

  $obj1 = new Test();
  $obj2 = new Test();

you have two variables refering to two different instances of Test.

While there's no functional difference, you probably should try to limit your use of the first one as you have no idea what could be inside $obj1 .

In both cases, you can then pass arguments and $obj2 is a separate object from $obj1 with the same class type.

Confusion with the new $obj1 format can arise when Test has a __toString method. In this case, the __toString method is not called, even though the usual case for the new $var() syntax is when $var is a string that has been generated or passed in.

In the first example, were you trying to set $obj2 as a reference to $obj1? If so, you should not use the new keyword or it will try to create a new object with a type stored in the $obj1 variable.

Creates two references to the same object:

$obj1 = new Test();
$obj2 = $obj1;//Creates a reference to the first object

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