This example describes the PHP object clone clone usage. Share to everyone for your reference, as follows:
Shallow clone: Only non-object non-resource data in the cloned object, that is, the object's property is stored in the object type, the clone will appear incomplete
<?phpclass b{Public $val = 10;} Class a{Public $val =, public $b, Public function __construct () { $this->b = new B ();}} $obj _a = new A () $obj _b = Clone $obj _a; $obj _a->val = $obj _a->b->val = 40;var_dump ($obj _a); Echo ' <br> '; v Ar_dump ($obj _b);
The results of the operation are as follows:
Object (a) [1] public ' val ' = = int-Public ' b ' = = object (b) [2] public ' val ' = + int + object (A) [3] public ' VA L ' = = int public ' b ' = = object (b) [2] public ' val ' + int 40
Deep Clone: All property Data of an object is copied completely, need to use magic Method __clone (), and implement deep clone inside
<?phpclass b{Public $val = 10;} Class a{Public $val =, 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 = $obj _a->b->val = 40;var_dump ($obj _a); Echo ' <br> '; v Ar_dump ($obj _b);
The results of the operation are as follows:
Object (a) [1] public ' val ' = = int-Public ' b ' = = object (b) [2] public ' val ' = + int + object (A) [3] public ' VA L ' = = int public ' b ' = = object (b) [4] public ' val ' + int 10
I hope this article is helpful to you in PHP programming.