淺克隆:只是克隆對像中的非對象非資源數據,即對像中屬性存儲的是對象類型,則會出現克隆不完全
<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教學有興趣的朋友有幫助。