PHP: Object Cloning – Manual

Change language: English Brazilian Portuguese Chinese (Simplified) French German Japanese Romanian Russian Spanish Turkish Other

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.

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.

__clone ( void ) : void

Once the cloning is complete, 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 #1 Cloning an object

publicfunction

publicfunction

class

function

print(

print(

The above example will output:

PHP 7.0.0 introduced the possibility to access a member of a freshly cloned object in a single expression:

Example #2 Access member of freshly cloned object

format('Y');?>

The above example will outputsomething similar to:

8 years ago


private

}

13 years ago

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.

12 years ago

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.

11 years ago

function

}

9 years ago

Another gotcha I encountered: like __construct and __desctruct, you must call parent::__clone() yourself from inside a child's __clone() function. The manual kind of got me on the wrong foot here: "An object's __clone() method cannot be called directly."

4 years ago

foreach (

public function

class

public function

echo

echo

3 years ago

public static

public function

public static function

public function

echo

unset(

echo

9 years ago

1. PHP treats variables as either 'values types' or 'reference types', where the difference is supposed to be transparent. Object cloning is one of the few times when it can make a big difference. I know of no programmatic way to tell if a variable is intrinsically a value or reference type. There IS however a non-programmatic ways to tell if an object property is value or reference type:

unset($ref);var_dump($a);

?>I interpret this as the reference-count jumping from 2 straight to 0. However...

2. It IS possible to create a reference with a reference count of 1 - i.e. to convert an property from value type to reference type, without any extra references. All you have to do is declare that it refers to itself. This is HIGHLY idiosyncratic, but nevertheless it works. This leads to the observation that although the manual states that 'Any properties that are references to other variables, will remain references,' this is not strictly true. Any variables that are references, even to *themselves* (not necessarily to other variables), will be copied by reference rather than by value.

Here's an example to demonstrate:

class ByVal{ var $prop;}

class ByRef{ var $prop; function __construct() { $this->prop =& $this->prop; }}

$a = new ByVal;$a->prop = 1;$b = clone $a;$b->prop = 2;

$a = new ByRef;$a->prop = 1;$b = clone $a;$b->prop = 2;

?>

9 months ago

public function

2 years ago

To illustrate this process, the following example codes seems better, comparing the the original version:

class SubObject{ static $num_cons = 0; static $num_clone = 0;

public $construct_value; public $clone_value;

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

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

class MyCloneable{ public $object1; public $object2;

function __clone() { // this->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);echo '
';print("Cloned Object:n");print_r($obj2);

==================

the output is as below

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

[object2] => SubObject Object ( [construct_value] => 2 [clone_value] => )

)
Cloned Object:MyCloneable Object( [object1] => SubObject Object ( [construct_value] => 1 [clone_value] => 1 )

[object2] => SubObject Object ( [construct_value] => 2 [clone_value] => )

)

11 years ago

Keep in mind that since PHP 5.2.5, trying to clone a non-object correctly results in a fatal error, this differs from previous versions where only a Warning was thrown.

3 years ago

I believe the two functions are not quite the same. The serialize followed by deserialize method is the way I've done deep cloning in other languages (bypasses any weird clone function behavior and ensures you have a no-strings-attached copy of the object).

10 years ago

$val) { if(is_object($val)||(is_array($val))){ $this->{$key} = unserialize(serialize($val)); } }}?>That will insure any object, or array that may potentially contain objects, will get cloned without using recursion or other support methods.

[EDIT BY danbrown AT php DOT net: An almost exact function was contributed on 02-DEC-2008-10:18 by (david ashe AT metabin):

$value){ if(gettype($value)=='object'){ $this->$name= clone($this->$name); } } }?>Giving credit where it's due. ~DPB][EDIT BY cmb AT php DOT net: the latter function fails to make deep copies of object arrays, and might end up with infinite recursion.]

Follow this link:

PHP: Object Cloning - Manual

Related Posts

Comments are closed.