From c43b87be6a21dfaa4a777c4673023fa9e77e1b1f Mon Sep 17 00:00:00 2001 From: Curt Zirzow Date: Sat, 7 Aug 2004 17:39:27 +0000 Subject: [PATCH] Be more clear how __clone() works (bug #27100), and example modifications. git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@165665 c90b9560-bf6c-de11-be94-00142212c4b1 --- language/oop5/cloning.xml | 98 +++++++++++++++++++++++++++++---------- 1 file changed, 74 insertions(+), 24 deletions(-) diff --git a/language/oop5/cloning.xml b/language/oop5/cloning.xml index ab90885f2c..d123b99510 100644 --- a/language/oop5/cloning.xml +++ b/language/oop5/cloning.xml @@ -1,5 +1,5 @@ - + Object cloning @@ -30,14 +30,13 @@ $copy_of_object = clone $object; - When the developer asks to create a new copy of an object, PHP 5 will check - if a __clone() method has been defined or not. If not, it will call a - default __clone() which will copy all of the object's properties. If a - __clone() method is defined, then it will be responsible to set the - necessary properties in the created object. For convenience, the engine - will supply a function that imports all of the properties from the source - object, so that they can start with a by-value replica of the source - object, and only override properties that need to be changed. + + 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. + @@ -45,34 +44,85 @@ $copy_of_object = clone $object; instance = ++self::$instances; + } + + public function __clone() { + $this->instance = ++self::$instances; + } +} + class MyCloneable { - static $id = 0; - function MyCloneable() { - $this->id = self::$id++; - } + public $object1; + public $object2; - function __clone() { - $this->address = "New York"; - $this->id = self::$id++; - } + function __clone() { + + // Force a copy of this->object, otherwise + // it will point to same object. + $this->object1 = clone($this->object1); + } } $obj = new MyCloneable(); -$obj->name = "Hello"; -$obj->address = "Tel-Aviv"; +$obj->object1 = new SubObject(); +$obj->object2 = new SubObject(); -print $obj->id . "\n"; +$obj2 = clone $obj; -$obj_cloned = clone $obj; -print $obj_cloned->id . "\n"; -print $obj_cloned->name . "\n"; -print $obj_cloned->address . "\n"; +print("Original Object:\n"); +print_r($obj); + +print("Cloned Object:\n"); +print_r($obj2); + ?> ]]> + &example.outputs; + + SubObject Object + ( + [instance] => 1 + ) + + [object2] => SubObject Object + ( + [instance] => 2 + ) + +) +Cloned Object: +MyCloneable Object +( + [object1] => SubObject Object + ( + [instance] => 3 + ) + + [object2] => SubObject Object + ( + [instance] => 2 + ) + +) +]]> + + +