第五节 克隆 [5]

  PHP5中的对象模型通过引用来调用对象, 但有时你可能想建立一个对象的副本,并希望原来的对象的改变不影响到副本 . 为了这样的目的,PHP定义了一个特殊的方法,称为__clone. 像__construct和__destruct一样,前面有两个下划线.

  默认地,用__clone方法将建立一个与原对象拥有相同属性和方法的对象. 如果你想在克隆时改变默认的内容,你要在__clone中覆写(属性或方法).

  克隆的方法可以没有参数,但它同时包含this和that指针(that指向被复制的对象). 如果你选择克隆自己,你要小心复制任何你要你的对象包含的信息,从that到this. 如果你用__clone来复制. PHP不会执行任何隐性的复制,

  下面显示了一个用系列序数来自动化对象的例子:  <?php

  class ObjectTracker file://对象跟踪器

  {

  private static $nextSerial = 0;

  private $id;

  private $name;

  function __construct($name) file://构造函数

  {

  $this->name = $name;

  $this->id = ++self::$nextSerial;

  }

  function __clone() file://克隆

  {

  $this->name = "Clone of $that->name";

  $this->id = ++self::$nextSerial;

  }

  function getId() file://获取id属性的值

  {

  return($this->id);

  }

  function getName() file://获取name属性的值

  {

  return($this->name);

  }

  }

  $ot = new ObjectTracker("Zeev's Object");

  $ot2 = $ot->__clone();

  //输出: 1 Zeev's Object

  print($ot->getId() . " " . $ot->getName() . "<br>");

  //输出: 2 Clone of Zeev's Object

  print($ot2->getId() . " " . $ot2->getName() . "<br>");

  ?>