Examples of $this and $that pointers used in PHP

Source: Internet
Author: User

A special method name "__clone ()" method is defined in PHP5. is a method that is invoked automatically when an object is cloned, using the "__clone ()" method to create an object with 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 In Clone () rewrite the original properties and methods, the "__clone ()" method can have no parameters, it automatically contains $this and $that two pointers, $this point to the copy, and the $that point to the original, specific examples are as follows:

The code is as follows:

Class Person {

The following are the member properties of the person

var $name; Person's name

var $sex; The gender of the person

var $age; The age of the person

Define a constructor parameter to assign the attribute 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 the way to speak his own attributes

function say () {

echo "My name is:". $this->name. "Sex:". $this->sex. "My Age is:". $this

->age. "

";

}

The method that is invoked automatically when the 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 () {

The copy of the $this refers to the P2, and the $that is pointing to the original P1, so that in this method, the properties of the copy are changed.

$this->name = "I am a copy of the John $that->name";

$this->age = 30;

}

}

$p 1 = new Person ("John", "Male", 20);

$p 2 = clone $p 1;

$p 1->say ();

$p 2->say ();

?>

The results of successfully running this PHP program are as follows:

The code is as follows:

My name is: John Sex: Male My age is: 20

My name is: I am a copy of John Sex: Male My age is: 20

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.