PHP object clone usage example

Source: Internet
Author: User
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!

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.