This article introduces the content of "PHP class and Object" Object replication, has a certain reference value, now share to everyone, the need for friends can refer to
Object replication
Usage scenarios:
1. If you have a GTK window object, the object holds the resources associated with the window. 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).
2. 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.
implementation: the __clone () method in the object cannot be called directly by using the Clone keyword (which, if possible, calls the object's __clone () method).
$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.
Example #1 Copy an object <?phpclass 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;p Rin T ("Original object:\n");p Rint_r ($obj);/*original object:mycloneable object ([Object1] = Subobject object ( [instance] + 1) [object2] = Subobject Object ([instance] = 2)) */print ("Cloned object:\n");p Rint_r ($obj 2);/*cloned object:mycloneable object ([Object1] = subobject Object ([instance] = 3) [Object2] = SubobjeCT Object ([instance] = 2)) */?>