Sometimes we need to use two or more identical objects in a project. If you use the "new" keyword to re-create the object and then assign the same attributes, this is more cumbersome and error-prone. , so it is very necessary to completely clone an identical object from an object, and after cloning, the two objects will not interfere with each other.
In PHP4 we use the keyword "clone" to clone objects;
02
04
//The following are the member attributes of people |
|
05
| var
$name ;
| //The person’s name
//Define a constructor parameter as the attribute name $name, gender $sex and age $age are assigned
|
10
|
function
__construct(
""
11
| ;name=
$name ;
12
$this ->sex= $sex ;
|
|
15
//This person can speak in a way that tells his own attributes
|
18
The son called: "
. $this |
->name .
" Gender: " . |
$this
->sex .
" My age is: "
21
|
22
$p1 = new Person( "张三" ,
"male" , 20);
|
24
//Clone using "clone" The new object p2 has the same properties and methods as the p1 object.
|
|
25
PHP4 defines a special method name "__clone()" method, which is automatically called when an object is cloned. Using the "__clone()" method will create an object with the same attributes and methods as the original object. If you want to To change the content of the original object after cloning, you need to rewrite the original attributes and methods in __clone(). The "__clone()" method can have no parameters. It automatically contains two pointers, $this and $that, and $this points to The copy , and $that points to the original;
04 | //The following are the member attributes of people |
var $sex ; | //Sex of a person
|
07
var $age ; | //Age of a person
|
08
| | //Define a constructor parameter as attributes name $name, gender $sex and age $age is assigned
$name
= "", | $sex= "" , $age = "" ) {
11
$name |
;
//The way this person can speak is to tell his own attributes
function
18
echo | "My name is:" . $this |
->name .
" Gender: "
.
$this
->sex .
" My age is: " |
. $this ->age .
" " |
;
//Method automatically called when an object is cloned. If you want to change the content of the original object after cloning, you need to rewrite the original attributes and methods in __clone()
function
23
|
24 |
//$this refers to the copy p2, and $that points to the original p1, so in this method, the attributes of the copy are changed.
|
25 |
$this ->name =
"I am fake $that->name" ;
|
"张三"
$p1
Output of the above example: Mine My name is: Zhang San Gender: Male My age is: 20 | My name is: I am the fake Zhang San Gender: Male My age is: 30
The above introduces the clone object in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.
|