PHP $this Pointer usage examples

Source: Internet
Author: User
a special method name, "Clone ()", is defined in the PHP5Object The method that is called automatically when cloning, with the "Clone ()" method will establish a same as the original objectProperties and Methods object, if you want to change the contents of the original object after cloning, you need to override the original property and method in Clone (), 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, The concrete examples are as follows:


<?phpclass person {    ///Below is a member of the human attribute    var $name;//person's name    var $sex;//Gender    var $age;//person's age              //define a constructor method Parameters for attribute name $name, gender $sex, and age $age are assigned              //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 speaks his own attribute    function say () {        echo "My name is:". $this->name. "Gender:". $this->sex. "My Age is:". $this        ->age. "<br>";    }    The method that is called automatically when the object is cloned, and if you want to change the contents of the original object after cloning, you need to override the original properties and Methods in Clone (). The    function clone () {        //$this refers to the replica P2, while $that is pointing to the original P1, so that in this method, the properties of the replica are changed.        $this->name = "I am a copy of Zhang San $that->name";        $this->age =;    }} $p 1 = new Person ("Zhang San", "male"), $p 2 = clone $p 1; $p 1->say (); $p 2->say (); >

The result of the successful operation of this PHP program is as follows:


My name is: Zhang San Sex: Male my age is:
My name is: I am copy of Zhang San Sex: Male my age is:

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.