PHP对象克隆clone PHP对象克隆clone用法示例
ligbee 人气:0想了解PHP对象克隆clone用法示例的相关内容吗,ligbee在本文为您仔细讲解PHP对象克隆clone的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:PHP,对象克隆,clone,下面大家一起来学习吧。
本文实例讲述了PHP对象克隆clone用法。分享给大家供大家参考,具体如下:
浅克隆:只是克隆对象中的非对象非资源数据,即对象中属性存储的是对象类型,则会出现克隆不完全
<?php class B{ public $val = 10; } class A{ public $val = 20; public $b; public function __construct(){ $this->b = new B(); } } $obj_a = new A(); $obj_b = clone $obj_a; $obj_a->val = 30; $obj_a->b->val = 40; var_dump($obj_a); echo '<br>'; var_dump($obj_b);
运行结果如下:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[2] public 'val' => int 40
深克隆:一个对象的所有属性数据都彻底的复制,需要使用魔术方法__clone(),并在里面实现深度克隆
<?php class B{ public $val = 10; } class A{ public $val = 20; public $b; public function __construct(){ $this->b = new B(); } public function __clone(){ $this->b = clone $this->b; } } $obj_a = new A(); $obj_b = clone $obj_a; $obj_a->val = 30; $obj_a->b->val = 40; var_dump($obj_a); echo '<br>'; var_dump($obj_b);
运行结果如下:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[4] public 'val' => int 10
希望本文所述对大家PHP程序设计有所帮助。
加载全部内容