This article mainly introduces the usage of PHP object clone, and analyzes the related concepts, features, and implementation methods of php shallow cloning and deep cloning based on the instance form, for more information, see the example in this article to describe how to clone PHP Objects. We will share this with you for your reference. The details are as follows:
Shortest cloning: only non-object and non-resource data in the cloned object, that is, the object type is stored in the property of the object, and incomplete cloning will occur.
b = new B(); }}$obj_a = new A();$obj_b = clone $obj_a;$obj_a->val = 30;$obj_a->b->val = 40;var_dump($obj_a);echo '
';var_dump($obj_b);
The running result is as follows:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[2] public 'val' => int 40
Deep cloning: all attribute data of an object is completely copied. you need to use the magic _ clone () method to perform in-depth cloning.
b = new B(); } public function __clone(){ $this->b = clone $this->b; }}$obj_a = new A();$obj_b = clone $obj_a;$obj_a->val = 30;$obj_a->b->val = 40;var_dump($obj_a);echo '
';var_dump($obj_b);
The running result is as follows:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[4] public 'val' => int 10
I hope this article will help you with PHP programming.
For more articles on clone usage examples of PHP Objects, refer to the Chinese PHP website!