Justin
Justin

Reputation: 1299

Does PHP duplicate objects on assignment?

Does PHP duplicate an object when = is used or does it just create a new pointer that points to an already existing object?

Are both of these the same?

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

$obj1 = new object(); 
$obj2 = clone $obj1;

Upvotes: 1

Views: 49

Answers (1)

lonesomeday
lonesomeday

Reputation: 237827

In PHP 4 (i.e. ancient history) objects were indeed copied on assignment. This was not helpful behaviour.

Since PHP 5, objects are now assigned by reference, unless they are cloned.

You can easily test this:

$obj1 = new object(); 
$obj2 = $obj1;
var_dump($obj1 === $obj2); // bool(true)

$obj1 = new object(); 
$obj2 = clone $obj1;
var_dump($obj1 === $obj2); // bool(false)

Upvotes: 5

Related Questions