Shallow cloning: only clone non-object non-resource data in the object, that is, the attributes in the object store the object type, then there will be incomplete cloning
<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>
Deep cloning: all attribute data of an object To completely copy, you need to use the magic method __clone(), and implement deep cloning in it
<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>
The above introduces PHP clone, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.