Lekhulal Mathalipara
Lekhulal Mathalipara

Reputation: 57

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...?

Upvotes: 1

Views: 109

Answers (3)

pythonjsgeo
pythonjsgeo

Reputation: 5411

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

Upvotes: 0

user3477804
user3477804

Reputation:

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.

Upvotes: 1

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

$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.

Upvotes: 1

Related Questions