清风徐来
知是行之始,行是知之成

PHP5的克隆方法

PHP cloneOOP 约 1 分钟

不多说了,代码注释里都有。

name 和 $this->id 是克隆出来的新对象的属性, 而赋值符(=)后面"Clone of $this->name"中的$this->name 是指被克隆的原对象的属性。 (貌似在php5前期的测试版中,克隆的方法同时包含this和that指针,that指向被复制的对象。 ) */ class ObjectTracker //对象跟踪器 { private static $nextSerial = 0; private $id; private $name; function __construct($name) //构造函数 { $this->name = $name; $this->id = ++self::$nextSerial; } function __clone() //克隆 { $this->name = "Clone of $this->name"; $this->id = ++self::$nextSerial; } function getId() //获取id属性的值 { return($this->id); } function getName() //获取name属性的值 { return($this->name); } } $ot = new ObjectTracker("Zeev's Object"); $ot2 = clone $ot; //输出: 1 Zeev's Object print($ot->getId() . " " . $ot->getName() . "
"); //输出: 2 Clone of Zeev's Object print($ot2->getId() . " " . $ot2->getName() . "
"); ?>