Home > Article > Backend Development > Detailed explanation of usage examples of $this pointer in PHP
PHP5 defines a special method name "clone()" method, which is automatically called when object is cloned. Use "clone()" The method will create an object with the same attributes and methods as the original object. If you want to change the content of the original object after cloning, you need to rewrite the original attributes and methods in clone() Method, the "clone()" method can have no parameters, it automatically contains two pointers, $this and $that, $this points to the copy, and $that points to the original, the specific example is as follows:
<?php class Person { // 下面是人的成员属性 var $name; // 人的名字 var $sex; // 人的性别 var $age; // 人的年龄 // 定义一个 构造方法 参数为属性姓名$name、性别$sex 和年龄$age 进行赋值 // function construct($name="", $sex="",$age="") function construct($name, $sex, $age) { $this->name = $name; $this->sex = $sex; $this->age = $age; } // 这个人可以说话的方法, 说出自己的属性 function say() { echo "我的名字叫:" . $this->name . " 性别:" . $this->sex . " 我的年龄是:" . $this ->age . "<br>"; } // 对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在clone()中重写原来的属性和方法。 function clone() { // $this 指的复本p2, 而$that 是指向原本p1,这样就在本方法里,改变了复本的属性。 $this->name = "我是复制的张三$that->name"; // $this->age = 30; } } $p1 = new Person ( "张三", "男", 20 ); $p2 = clone $p1; $p1->say (); $p2->say (); ?>
The results after successfully running this PHP program are as follows:
My name is: Zhang San Gender: Male My age Is: 20
My name is: I am copied Zhang San Gender: Male My age is: 20
The above is the detailed content of Detailed explanation of usage examples of $this pointer in PHP. For more information, please follow other related articles on the PHP Chinese website!