Usage examples of $this and $that pointers in PHP, that pointer
PHP5 defines a special method named "__clone()", 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 change the contents of the original object after cloning, you need to rewrite the original properties and methods in __clone(). 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:
Copy code The code is as follows:
class Person {
//The following are the member attributes of people
var $name; // person’s name
var $sex; // Person’s gender
var $age; // The person’s age
// Define a constructor parameter to assign values to the attributes name $name, gender $sex and age $age
// function __construct($name="", $sex="",$age="")
Function __construct($name, $sex, $age) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
//The way this person can speak is to tell his own attributes
Function say() {
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 contents of the original object after cloning, you need to rewrite the original properties and methods in __clone().
Function __clone() {
// $this refers to the copy p2, and $that points to the original p1, so in this method, the attributes of the copy are changed.
$this->name = "I am the copied Zhang San$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:
Copy code The code is 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
http://www.bkjia.com/PHPjc/938858.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/938858.htmlTechArticleUsage examples of $this and $that pointers in PHP. The that pointer defines a special method name "__clone" in PHP5 ()" method is a method that is automatically called when an object is cloned. Use the "__clone()" method...