ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ <?php class SubObject { public 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; public function __clone() { // 强制复制一份this->object, 否则仍然指向同一个对象 $this->object2 = clone $this->object1; } } $obj = new MyCloneable(); $obj->object1 = new SubObject(); $obj->object2 = new SubObject(); new SubObject(); $aaa = new SubObject(); echo($aaa->instance) . '<br>'; $obj2 = clone $obj; echo "Original Object:\n"; echo $obj; echo "Cloned Object:\n"; echo $obj2; ~~~ php的 **\_\_clone()** 方法对一个对象实例进行的浅复制,对象内的基本数值类型进行的是传值复制,而对象内的对象型成员变量,如果不重写 **\_\_clone** 方法,显式的clone这个对象成员变量的话,这个成员变量就是**传引用复制**,而不是生成一个新的对象. ~~~ <?php class Account { public $balance; public function __construct($balance) { $this->balance = $balance; } } class Person { private $id; private $name; private $age; public $account; public function __construct($name, $age, Account $account) { $this->name = $name; $this->age = $age; $this->account = $account; } public function setId($id) { $this->id = $id; } public function __clone() { //复制方法,可在里面定义再clone是进行的操作 $this->id = 0; $this->account = clone $this->account; //不加这一句,account在clone是会只被复制引用,其中一个account的balance被修改另一个也同样会被修改 } } $person = new Person('peter', 15, new Account(1000)); $person->setId(1); $person2 = clone $person; $person2->account->balance = 250; dump($person, $person2); ~~~