PHP object clone clone keyword with _clone () step

Source: Internet
Author: User
PHP object clone clone keyword and __clone () method
The Clone keyword is used to clone an identical object, and the __clone () method overrides the original property and method.

Object cloning

Sometimes we need to use two or more of the same objects in a project, and it is cumbersome and error-prone to re-create objects with the New keyword and assign the same properties. PHP provides the object cloning function, can be based on an object to completely clone an identical object, and after cloning, two objects do not interfere with each other.

Use the keyword clone to clone an object. Grammar:
$object 2 = Clone $object;


Example:
 
  Name= $name;        $this->age= $age;    }    function say () {        echo "My name is:". $this->name. "
"Echo" My Age is: ". $this->age; }} $p 1 = new Person ("Zhang San"), $p 2 = clone $p 1; $p 2->say (); >


To run an example, output:
My name is: Zhang San my age is: 20


__clone ()

If you want to change the contents of the original object after cloning, you need to add a special __clone () method to the class to override the original properties and methods. The __clone () method will only be called automatically when the object is cloned.

Example:
 
  name = $name;        $this->age = $age;    }    function say () {        echo "My name is:". $this->name;echo "My Age is:". $this->age. "
"; } function __clone () { $this->name = "I am false". $this->name; $this->age =; }} $p 1 = new Person ("Zhang San"), $p 1->say (), $p 2 = clone $p 1; $p 2->say ();? >


To run an example, output:
My name is: Zhang San my age is: 20 My name is: I am false Zhang San my age is: 30

1/F meihaoderizi123 2012-08-14

Thanks,this article is very helpful to me.

  • 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.