Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Language Reference : Classes and Objects (PHP 5) : Object cloning

Object cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Example 10.31. Cloning an object

<?php
class SubObject
{
   static
$instances = 0;
   public
$instance;

   public function
__construct() {
       
$this->instance = ++self::$instances;
   }

   public function
__clone() {
       
$this->instance = ++self::$instances;
   }
}

class
MyCloneable
{
   public
$object1;
   public
$object2;

   function
__clone()
   {
       
// Force a copy of this->object, otherwise
       // it will point to same object.
       
$this->object1 = clone $this->object1;
   }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print(
"Original Object:\n");
print_r($obj);

print(
"Cloned Object:\n");
print_r($obj2);

?>

The above example will output:

Original Object:
MyCloneable Object
(
   [
object1] => SubObject Object
       
(
           [
instance] => 1
       
)

   [
object2] => SubObject Object
       
(
           [
instance] => 2
       
)

)
Cloned Object:
MyCloneable Object
(
   [
object1] => SubObject Object
       
(
           [
instance] => 3
       
)

   [
object2] => SubObject Object
       
(
           [
instance] => 2
       
)

)
?>


Code Examples / Notes » language.oop5.cloning

alexey

To implement __clone() method in complex classes I use this simple function:
function clone_($some)
{
  return (is_object($some)) ? clone $some : $some;
}
In this way I don't need to care about type of my class properties.


mr.kto

In PHP4 the clone keyword isn't defined, if you want a compatible code (using a copy of an object) - use this fix:
$c = (PHP_VERSION < 5) ? $b : clone($b);
It is possible cause php checks function existence just before its calling.


muratyaman

I think this is a bit awkward:
<?php
class A{
public $aaa;
}
class B{
public $a;
public $bbb;

function __clone(){
$this->a = clone $this->a;//clone MANUALLY!!!
}
}
$b1 = new B();
$b1->a = new A();
$b1->a->aaa = 111;
$b1->bbb = 1;
$b2 = clone $b1;
$b2->a->aaa = 222;//BEWARE!!
$b2->bbb = 2;//no problem on basic types
var_dump($b1); echo '<br />';
var_dump($b2);
/*
OUTPUT BEFORE implementing the function __clone()
object(B)#2 (3) { ["a"]=>  object(A)#3 (1) { ["aaa"]=>  int(222) } ["bbb"]=>  int(1)  }
object(B)#4 (3) { ["a"]=>  object(A)#3 (1) { ["aaa"]=>  int(222) } ["bbb"]=>  int(2)  }
OUTPUT AFTER implementing the function __clone()
object(B)#1 (3) { ["a"]=>  object(A)#2 (1) { ["aaa"]=>  int(111) } ["bbb"]=>  int(1)  }
object(B)#3 (3) { ["a"]=>  object(A)#4 (1) { ["aaa"]=>  int(222) } ["bbb"]=>  int(2)  }
*/
?>
Whenever we use another class inside, we must clone it manually. If you have 10s of classes related, this is rather tedious. I don't want to even think about classes dynamically populated with other objects. Be careful when designing your classes! You should look after your objects all the time! This major change on PHP5 vs PHP4 regarding "references" definitely has very good performance improvements but comes with very dangerous side effects as well..


jorge dot villalobos

I think it's relevant to note that __clone is NOT an override. As the example shows, the normal cloning process always occurs, and it's the responsibility of the __clone method to "mend" any "wrong" action performed by it.

makariverslund

I ran into the same problem of an array of objects inside of an object that I wanted to clone all pointing to the same objects. However, I agreed that serializing the data was not the answer. It was relatively simple, really:
   public function __clone()
   {
       foreach ($this->varName as &$a)
{
           foreach ($a as &$b)
   {
$b = clone $b;
   }
}
   }
Note, that I was working with a multi-dimensional array and I was not using the Key=>Value pair system, but basically, the point is that if you use foreach, you need to specify that the copied data is to be accessed by reference.


paul

I noticed when trying to clone a series of objects in a loop and and adding them to an array, the objects were still passed by reference, so all objects took the same value as the last object cloned and added to the array.
The solution was to use the copy function as below which truly clones objects.
Here is an example:
<?php
$temp = new $this->_doname;
foreach($rows as $id=>$row) {
       $do = clone $temp;
       $do->load($id);
       $this->_dataobjects[]= clone $do;
}
?>
This results in every object having the same value.
However using:
<?php
$this->_dataobjects[]= $this->copy($do);
?>
with
<?php
public function copy()
{
  $serialized_contents = serialize($this);
  return unserialize($serialized_contents);
}
?>
Actually produces the expected result.
Paul Bain


markus dot amsler

For php4 you can use the clone method from the PEAR PHP_Compat package (http://pear.php.net/package/PHP_Compat).

felix gilcher

Copying objects with
<?php
public function copy()
{
  $serialized_contents = serialize($this);
  return unserialize($serialized_contents);
}
?>
is a pretty dangerous thing. What if your objects hold references to very large shared objects? They all get copied as well. Serializing objects may break database connections and references. What you probably want to do is implement a proper __clone() method for each of your classes so that each object in your tree gets to decide what subobjects need to be copied and which ones should better remain untouched.
regards
felix


ove

Consider this:
function myfunc()
{
   $A = new myobject(); // Create another mysql connection
   $A->method1();         // Runs a query (works)
}
$A = new myobject(); // Create a mysql connection
myfunc();
$A->method1();  // This query fails! Possible because leaving the function has closed the connection.
Conclusion: Declaration of objects within and outside a function WITH THE SAME NAME, will affect each other. Do not relay on the rules of scope.
Take care when using recursive structures!!
It took me a long time to figure out.


olle dot remove_this dot suni

As jorge dot villalobos at gmail dot com pointed out, the "__clone is NOT an override".
However, if one needs a true copy of an object (which has real copies of all subobjects too, not references), one can define a class method such as this to the object-to-be-cloned:
public function copy()
{
   $serialized_contents = serialize($this);
   return unserialize($serialized_contents);
}
The method makes a string representation of the object's contents (including subobjects), which can then be unserialized back to an object.
The method usage is simple:
$original_object = new MyCloneable(); //can have sub objects
$copied_object = $original_object->clone(); //only makes copies of the values, not references
With serialization, you surely don't have to worry about references, since serialized object is just simple text.


Change Language


Follow Navioo On Twitter
Introduction
The Basics
Autoloading Objects
Constructors and Destructors
Visibility
Scope Resolution Operator (::)
Static Keyword
Class Constants
Class Abstraction
Object Interfaces
Overloading
Object Iteration
Patterns
Magic Methods
Final Keyword
Object cloning
Comparing objects
Reflection
Type Hinting
Late Static Bindings
eXTReMe Tracker