对象复制。有什么不同?

时间:2013-11-22 12:39:09

标签: php object clone

在下面的例子中......我在这里有些困惑

<?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关键字?

1 个答案:

答案 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 这两个变量是同一个实例。