오늘 다화의 디자인 패턴을 보다가 프로토타입 패턴을 봤습니다. 딥카피(Deep Copy)와 얕은 카피(Shallow Copy)에 대해 이야기하고 있어서 PHP 매뉴얼을 찾아보았습니다.
PHP가 전체 복사와 얕은 복사를 구현하는 방법을 알아보세요.
<code><span><span>class</span><span>SubObject</span> {</span><span>static</span><span>$instances</span> = <span>0</span>; <span>public</span><span>$instance</span>; <span>public</span><span><span>function</span><span>__construct</span><span>()</span> {</span><span>$this</span>->instance = ++ <span>self</span>::<span>$instances</span>; } <span>public</span><span><span>function</span><span>__clone</span><span>()</span> {</span><span>$this</span>->instance = ++<span>self</span>::<span>$instances</span>; } } <span><span>class</span><span>MyCloneable</span> {</span><span>public</span><span>$object1</span>; <span>public</span><span>$object2</span>; <span>public</span><span><span>function</span><span>__clone</span><span>()</span> {</span><span>// 强制复制一份this->object, 否则仍然指向同一个对象</span><span>// 深复制[将自己的属性重新克隆一份]</span><span>$this</span>->object1 = <span>clone</span><span>$this</span>->object1; <span>// 浅复制[引用的还是原来,并没有生成新的]</span><span>//$this->object2 = clone $this->object2;</span> } } <span>$obj</span> = <span>new</span> MyCloneable(); <span>$obj</span>->object1 = <span>new</span> SubObject(); <span>$obj</span>->object2 = <span>new</span> SubObject(); <span>$obj2</span> = <span>clone</span><span>$obj</span>; <span>print</span>(<span>"Original Object:\n"</span>); print_r(<span>$obj</span>); <span>print</span>(<span>"Clone Object:\n"</span>); print_r(<span>$obj2</span>);</code>
결과
<code>Original Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => <span>1</span> ) [object2] => SubObject Object ( [instance] => <span>2</span> ) ) <span>Clone</span> Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => <span>3</span><span>//深复制 所以有+1</span> ) [object2] => SubObject Object ( [instance] => <span>2</span><span>//浅复制 并没有创建新的对象</span> ) ) </code>
위 내용은 PHP Clone Deep Copy와 Shallow Copy를 포함하여 Clone 및 PHP 콘텐츠를 소개하는 내용으로, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.