In most cases, we do not need to completely copy an object to get its properties. But there is one case where it really needs to be: If you have a GTK window object, the object holds the window-related resources. You may want to copy a new window, keeping all properties the same as the original window, but it must be a new object (because if it is not a new object, the change in one window will affect the other window). Another case: If object A holds a reference to object B, when you copy object A, the object you want to use is no longer an object B but a copy of B, then you must get a copy of object A. Object replication can be done by using the Clone keyword (which, if possible, calls the object's __clone () method). The __clone () method in the object cannot be called directly.
$copy _of_object = Clone $object;
When the object is copied, PHP 5 performs a shallow copy of all the properties of the object (shallow copy). All reference properties will still be a reference to the original variable.
void __clone (void)
When the copy is complete, if the __clone () method is defined, the __clone () method in the newly created object (copy generated object) is called and can be used to modify the value of the property, if necessary.
Copy 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 $object 1; Public $object 2; function __clone () { //forces a copy of This->object, otherwise it still points to the same object $this->object1 = Clone $this Object1; } } $obj = new mycloneable (); $obj->object1 = new Subobject (); $obj->object2 = new Subobject (); $obj 2 = clone $obj; Print ("Original object:\n"); Print_r ($obj); Print ("Cloned object:\n"); Print_r ($obj 2);? >
The above routines 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 ))