分享PHP手册上 关于对象克隆的例子
<?php
class SubObject
{
static $instances = 0;
public $instance;
public function __construct() {
$this->instance = ++self::$instances;
}
public function __clone() {
$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
// 强制复制一份this->object, 否则仍然指向同一个对象
$this->object1 = clone $this->object1;
}
}
$obj = new MyCloneable(); //第一步
$obj->object1 = new SubObject(); //第二步
$obj->object2 = new SubObject();
$obj2 = clone $obj; //第三步
print_r($obj);
print_r($obj2);
第一步:
$obj = new MyCloneable();
这里$obj是MyCloneable的对象
MyCloneable Object
(
[object1] =>
[object2] =>
)
第二步:
$obj-