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 () 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{
public
function
__clone(){
echo
"对象已被克隆"
;
}
}
$objectA
=
new
MyClone();
$objectB
=
$objectA
;
//不调用__clone()方法,没任何输出
$objectC
=
clone
$objectA
;
//调用__clone()方法
|
The program executes the result: The object has been cloned
PHP Classes and objects: Clone cloning