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.