首页 > 后端开发 > php教程 > PHP之克隆clone

PHP之克隆clone

WBOY
发布: 2016-07-29 09:02:19
原创
1022 人浏览过

浅克隆:只是克隆对象中的非对象非资源数据,即对象中属性存储的是对象类型,则会出现克隆不完全

<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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板