1

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

2
  • Yes, you can pass construct parameter with direct class call. Commented Apr 30, 2014 at 6:23
  • Although there is no difference, you should not reinstantiate this way. In practice, using the first one is only when creating an object on the fly from string, but not from already created object. The practical use could be $class = 'Test'; $obj = new $class Commented Apr 30, 2014 at 6:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

6 Comments

In both cases in the question $obj1 is a different object from $obj2.
Thanks Sajad. I just noticed from php.net/manual/en/language.oop5.basic.php. Would you please explain me the below lines of code in detail $obj1 = new Test(); $obj2 = new $obj1; as compared to $obj1 = new Test(); $obj2 = new Test();
Objects are only equivalent if they both refer to the same instance.
@simon Are $obj1 and $obj2 the object of same class? And do they have same properties?
@LekhulalMathalipara:didn't my answer helped ? why the downvote?
|
0

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

1 Comment

No, he is just asking whats the difference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.