PHP Object Clone Clone Usage Example

Source: Internet
Author: User
Tags php programming
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.