Sometimes we need to use two or more of the same objects in a project, if you re-create the object using the "new" keyword, then assign the same attributes, it is cumbersome and error-prone, so it is necessary to completely clone an object exactly as it is, And after cloning, two objects do not interfere with each other.
In PHP4 we use the "clone" keyword to clone the object;
09 |
//定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 |
10 |
function__construct($name= "", $sex= "", $age= "") { |
18 |
echo"我的名子叫:". $this->name ." 性别:". $this->sex ." 我的年龄是:". $this->age ." "; |
22 |
$p1= newPerson("张三","男", 20); |
24 |
//使用“clone”克隆新对象p2,和p1对象具有相同的属性和方法。 |
PHP4 defines a special method named "__clone ()" method, which is the method that is called automatically when the object is cloned, and the "__clone ()" method will establish an object that has the same properties and methods as the original object, and if you want to change the contents of the original object after cloning, you need to __clone () Overriding the original properties and methods, the "__clone ()" method can have no parameters, it automatically contains $this and $that two pointers, $this point to the replica , and $that point to the original ;
09 |
//定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 |
10 |
function__construct($name= "", $sex= "", $age= "") { |
18 |
echo"我的名子叫:". $this->name ." 性别:". $this->sex ." 我的年龄是:". $this->age ." "; |
21 |
//对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在__clone()中重写原本的属性和方法 |
24 |
//$this指的复本p2, 而$that是指向原本p1,这样就在本方法里,改变了复本的属性。 |
25 |
$this->name ="我是假的 $that->name"; |
31 |
$p1= newPerson("张三","男", 20); |
The above example outputs:
My name is called: Zhang San Sex: Male my age is: 20
My name is called: I am false zhang San Sex: Male my age is:
The above describes the clone object in PHP, including the contents of the content, I hope that the PHP tutorial interested in a friend helpful.