首頁 > 後端開發 > php教程 > PHP之克隆clone

PHP之克隆clone

WBOY
發布: 2016-07-29 09:02:19
原創
1014 人瀏覽過

淺克隆:只是克隆對像中的非對象非資源數據,即對像中屬性存儲的是對象類型,則會出現克隆不完全

<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>
登入後複製

PHP之克隆clone

深克隆:一個對象的所有屬性數據都徹底的複製,需要使用魔術方法__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

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介紹了PHP之克隆clone,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板