PHP Classes and objects: Clone cloning

Source: Internet
Author: User

Objects can also be "cloned"

In PhP5, the way an object is passed by default is a reference pass, and if we want to generate two identical objects in memory or create a copy of an object, you can use clone.

Cloning an object from clone

The copy of the object is implemented by using the keyword clone. Cloning an object with clone has nothing to do with the original object, it is a copy of the original object from the current location, which is equivalent to a new space in memory. You can clone an object by using the keyword clone, which has the following syntax:

$克隆对象名称=clone$原对象名称;
__clone () method

The __clone () method of an object cannot be called directly, and can be used to invoke the __clone () method only if an object is cloned by using the keyword clone. When you create a copy of an object, PHP5 checks to see if the __clone () method exists. If it does not exist, it invokes the default __clone () method, copying all properties of the object. If the __clone method is already defined, then the __clone () method is responsible for setting the properties of the new object. So in the __clone () method, you just need to overwrite the attributes that need to be changed. Examples are as follows:

class MyClone{    publicfunction__clone(){        echo"对象已被克隆";    }}$objectA=newMyClone();$objectB=$objectA;  //不调用__clone()方法,没任何输出$objectC=clone$objectA;  //调用__clone()方法

The program executes the result: The object has been cloned

PHP Classes and objects: Clone cloning

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.