First, the PHP object clone reference:
Http://php.net/manual/en/language.oop5.cloning.php#object.clone
Object cloning¶
Creating a copy of a object with fully replicated properties are not always the wanted behavior. A Good example of the need for copy constructors, are if you had an object which represents a GTK window and the object ho LDS the resource of this GTK windows when you create a duplicate you might want to create a new window with the same prope Rties and has 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 Obje CT want to create a new instance of this and object so, the replica have its own separate copy.
An object copy was created by using the clone keyword (which calls the object ' s __clone () method if possible). An object ' s __clone () method cannot is called directly.
$copy _of_object = Clone $object;
When an object is cloned, PHP 5 would perform a shallow copy of all of the object's properties. Any properties that is references to other variables would remain references.
void __clone (void)
Once The cloning is complete, if a __clone () method was defined, then the newly created object ' s __clone () method would be C Alled, to-allow any necessary properties, which need to be changed.
Example #1 cloning an object
<?PHPclasssubobject{Static $instances= 0; Public $instance; Public function__construct () {$this->instance = ++self::$instances; } Public function__clone () {$this->instance = ++self::$instances; }}classmycloneable{ Public $object 1; Public $object 2; function__clone () {//Force A copy of This->object, otherwise//it would point to same object. $this->object1 =Clone $this-Object1; }}$obj=Newmycloneable ();$obj->object1 =Newsubobject ();$obj->object2 =Newsubobject ();$obj 2=Clone $obj;Print("Original object:\n");Print_r($obj);Print("Cloned object:\n");Print_r($obj 2);?>
The above example would output:
OriginalObject:mycloneableObject([Object1]= SubobjectObject([instance]= 1) [Object2]= SubobjectObject([instance]= 2)) ClonedObject:mycloneableObject([Object1]= SubobjectObject([instance]= 3) [Object2]= SubobjectObject([instance]= 2 ))
PHP, in fact, with the clone keyword plus __clone () can be achieved shallow copy and deep copy, __clone () method is the abstraction of the interface.
Big Talk Design pattern Nineth Chapter---The Prototype pattern PHP implementation