The example in this article describes the usage of PHP object cloning clone. Share it with everyone for your reference, the details are as follows:
Shallow cloning: only clone the non-object non-resource data in the object, that is, the attributes in the object store the object type, then there will be incomplete cloning
<?php class B{ public $val = 10; } class A{ public $val = 20; public $b; public function __construct(){ $this->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 '<br>'; var_dump($obj_b);
Run The results are 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 are completely copied. You need to use the magic method __clone(), and implement deep cloning in it
<?php class B{ public $val = 10; } class A{ public $val = 20; public $b; public function __construct(){ $this->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 '<br>'; var_dump($obj_b);
The running results are 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 be helpful to everyone in PHP programming.
For more articles related to PHP object cloning clone usage examples, please pay attention to the PHP Chinese website!