Home  >  Article  >  php教程  >  PHP中$this和$that指针使用实例

PHP中$this和$that指针使用实例

WBOY
WBOYOriginal
2016-06-13 09:05:471109browse

PHP中$this和$that指针使用实例

   PHP5中定义了一个特殊的方法名“__clone()”方法,是在对象克隆时自动调用的方法,用“__clone()”方法将建立一个与原对象拥有相同属性和方法的对象,如果想在克隆后改变原对象的内容,需要在__clone()中重写原本的属性和方法,“__clone()”方法可以没有参数,它自动包含$this和$that两个指针,$this指向复本,而$that指向原本,具体实例如下:

  代码如下:

  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 . "

  ";

  }

  // 对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在__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 ();

  ?>

  成功运行此PHP程序后的结果如下:

  代码如下:

  我的名字叫:张三 性别:男 我的年龄是:20

  我的名字叫:我是复制的张三 性别:男 我的年龄是:20

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