首页 > 后端开发 > php教程 > PHP Clone 深复制和浅复制 clclone hdclone memberwiseclon

PHP Clone 深复制和浅复制 clclone hdclone memberwiseclon

WBOY
发布: 2016-07-29 08:54:05
原创
1444 人浏览过

今天在看大话设计模式的时候,看到原型模式。其中讲到深复制与浅复制,于是搜索了一下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>
登录后复制
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了PHP Clone 深复制和浅复制,包括了clone,php方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板