Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object copy versus clone in PHP

Tags:

object

clone

php

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.

like image 849
ddamasceno Avatar asked Aug 07 '11 12:08

ddamasceno


People also ask

What is object clone in PHP?

The clone keyword is used to create a copy of an object. If any of the properties was a reference to another variable or object, then only the reference is copied. Objects are always passed by reference, so if the original object has another object in its properties, the copy will point to the same object.

Does PHP support object cloning?

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). $copy_of_object = clone $object; When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

Can you copy an object?

In object-oriented programming, object copying is creating a copy of an existing object, a unit of data in object-oriented programming. The resulting object is called an object copy or simply copy of the original object. Copying is basic but has subtleties and can have significant overhead.


1 Answers

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.

like image 94
deceze Avatar answered Sep 21 '22 00:09

deceze