首页  >  文章  >  后端开发  >  PHP对象克隆clone用法示例

PHP对象克隆clone用法示例

高洛峰
高洛峰原创
2016-12-21 14:04:421179浏览

本文实例讲述了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 &#39;<br>&#39;;
var_dump($obj_b);

   

运行结果如下:

object(A)[1]
 public &#39;val&#39; => int 30
 public &#39;b&#39; =>
 object(B)[2]
  public &#39;val&#39; => int 40
 
object(A)[3]
 public &#39;val&#39; => int 20
 public &#39;b&#39; =>
 object(B)[2]
  public &#39;val&#39; => 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 &#39;<br>&#39;;
var_dump($obj_b);

   

运行结果如下:

object(A)[1]
 public &#39;val&#39; => int 30
 public &#39;b&#39; =>
 object(B)[2]
  public &#39;val&#39; => int 40
 
object(A)[3]
 public &#39;val&#39; => int 20
 public &#39;b&#39; =>
 object(B)[4]
  public &#39;val&#39; => int 10

   

希望本文所述对大家PHP程序设计有所帮助。

更多PHP对象克隆clone用法示例相关文章请关注PHP中文网!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn