Home >Backend Development >PHP Tutorial >Examples of using $this and $that pointers in PHP_PHP Tutorial

Examples of using $this and $that pointers in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 09:55:32733browse

Examples of using $this and $that pointers in PHP

PHP5 defines a special method name "__clone()" method, which is automatically used when an object is cloned The method called, using the "__clone()" 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() , 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:

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;

 }

// This person can speak in a way that tells 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 content of the original object after cloning, you need to rewrite the original attributes and methods in __clone().

Function __clone() {

  // $this points 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:

The code is as follows:

My name is: Zhang San Gender: Male My age is: 20

My name is: I am a copy of Zhang San Gender: Male My age is: 20

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/991644.htmlTechArticleUsage examples of $this and $that pointers in PHP PHP5 defines a special method name __clone() method , is a method automatically called when an object is cloned. Use the __clone() method to create a pair with the original...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn