PHP之克隆clone

WBOY
Lepaskan: 2016-07-29 09:02:19
asal
1022 orang telah melayarinya

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

<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>
Salin selepas log masuk

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>
Salin selepas log masuk

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教程有兴趣的朋友有所帮助。

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan