1
在下面的例子..我有一些困惑這兒對象複製。有什麼不同?
<?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
關鍵字?