Alex Rivera | Logout

Object copy versus clone in PHP

Asked 2011-08-07T12:37:00.573
26

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.

Edit
Report

1 Answer

37

Yes, that's normal. Objects are always "assigned" by reference in PHP5. To actually make a copy of an object, you need to clone it.

To be more correct though, let me quote the manual:

As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

answered 2011-08-07T12:41:17.233

Your Answer