在下面的例子中......我在这里有些困惑
<?php
class SubObject
{
static $instances = 0;
public $instance;
public function __construct() {
$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
$this->object1 = clone $this->object1;
$this->object2 = clone $this->object2;
}
}
$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;//If i use $obj2 = $obj; it does return the same results.
print("Original Object:\n");
print_r($obj);
print("Cloned Object:\n");
print_r($obj2);
执行$obj2 = clone $obj;
和$obj2 = $obj;
之间有什么区别?两者都返回相同的结果。那么我为什么要使用clone
关键字?
答案 0 :(得分:0)
$obj2 = clone $obj
var_dump($obj === $obj2); // bool(false)
它会根据MyCloneable
创建一个新的$obj
实例,并将其存储到$obj2
。
每个变量都包含MyCloneable
。
$obj2 = $obj
var_dump($obj === $obj2); // bool(true)
上述声明会将$obj
分配到$obj2
这两个变量是同一个实例。