Object copy versus clone in PHP

Viewed 39951

Consider the following:

$object1 = new stdClass();
$object2 = $object1;
$object3 = clone $object1;

$object1->content = 'Ciao';

var_dump($object1);
 // Outputs object(stdClass)#1 (1) { ["content"]=> string(4) "Ciao" }
var_dump($object2);
 // Outputs object(stdClass)#1 (1) { ["content"]=> string(4) "Ciao" }
var_dump($object3);
 // Outputs object(stdClass)#2 (0) { }

Is it a normal PHP behavior that $object2 has a content identical to $object1 ?

To me it sound like $object2 is a reference to $object1 instead of a copy. Cloning the object before changing the content does act like a copy. This behavior is different than what happens with variables and seems unintuitive to me.

4 Answers
Related