浅克隆:只是克隆对象中的非对象非资源数据,即对象中属性存储的是对象类型,则会出现克隆不完全
<code><span><span><?php </span><span><span>class</span><span>B</span>{</span><span>public</span><span>$val</span> = <span>10</span>; } <span><span>class</span><span>A</span>{</span><span>public</span><span>$val</span> = <span>20</span>; <span>public</span><span>$b</span>; <span>public</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>$this</span>->b = <span>new</span> B(); } } <span>$obj_a</span> = <span>new</span> A(); <span>$obj_b</span> = <span>clone</span><span>$obj_a</span>; <span>$obj_a</span>->val = <span>30</span>; <span>$obj_a</span>->b->val = <span>40</span>; var_dump(<span>$obj_a</span>); <span>echo</span><span>'<br>'</span>; var_dump(<span>$obj_b</span>);</span></span></code>
深克隆:一个对象的所有属性数据都彻底的复制,需要使用魔术方法__clone(),并在里面实现深度克隆
<code><span><span><?php </span><span><span>class</span><span>B</span>{</span><span>public</span><span>$val</span> = <span>10</span>; } <span><span>class</span><span>A</span>{</span><span>public</span><span>$val</span> = <span>20</span>; <span>public</span><span>$b</span>; <span>public</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>$this</span>->b = <span>new</span> B(); } <span>public</span><span><span>function</span><span>__clone</span><span>()</span>{</span><span>$this</span>->b = <span>clone</span><span>$this</span>->b; } } <span>$obj_a</span> = <span>new</span> A(); <span>$obj_b</span> = <span>clone</span><span>$obj_a</span>; <span>$obj_a</span>->val = <span>30</span>; <span>$obj_a</span>->b->val = <span>40</span>; var_dump(<span>$obj_a</span>); <span>echo</span><span>'<br>'</span>; var_dump(<span>$obj_b</span>);</span></span></code>
以上就介绍了PHP之克隆clone,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。