new
关键字重新创建对象,再为属性赋上相同的值,这样做会比较烦琐而且也容易出错。在 PHP 中可以根据现有的对象克隆出一个完全一样的对象,克隆以后,原本对象和副本对象是完全独立互不干扰的。克隆对象名称 = clone 原对象名称;
因为 clone 的方式实际上是对整个对象的内存区域进行了一次复制并用新的对象变量指向新的内存,因此赋值后的对象和原对象之间是相互独立的。<?php class Website{ public $name, $url; public function __construct($name, $url){ $this -> name = $name; $this -> url = $url; } public function output(){ echo $this -> name.','.$this -> url.'<br>'; } } $obj = new Website('C语言中文网', 'http://c.biancheng.net/php/'); $obj2 = clone $obj; $obj -> output(); $obj2 -> output(); echo '<pre>'; var_dump($obj); var_dump($obj2); ?>运行结果如下:
C语言中文网,http://c.biancheng.net/php/
C语言中文网,http://c.biancheng.net/php/
object(Website)#1 (2) {
["name"]=>
string(16) "C语言中文网"
["url"]=>
string(27) "http://c.biancheng.net/php/"
}
object(Website)#2 (2) {
["name"]=>
string(16) "C语言中文网"
["url"]=>
string(27) "http://c.biancheng.net/php/"
}
注意:如果使用 =
将一个对象赋值给一个变量,那么这时得到的将是一个对象的引用,通过这个变量更改属性的值将会影响原来的对象。
<?php class Website{ public $name, $url; public function __construct($name, $url){ $this -> name = $name; $this -> url = $url; } public function output(){ echo $this -> name.','.$this -> url.'<br>'; } public function __clone(){ $this -> name = 'PHP教程'; $this -> url = 'http://c.biancheng.net/'; } } $obj = new Website('C语言中文网', 'http://c.biancheng.net/php/'); $obj2 = clone $obj; $obj -> output(); $obj2 -> output(); ?>运行结果如下:
C语言中文网,http://c.biancheng.net/php/
PHP教程,http://c.biancheng.net/
提示:如果在类中设置一个空的,访问权限为 private(私有的)的 __clone() 方法的话,可以起到禁止克隆的作用。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有