PHP之克隆clone

WBOY
Libérer: 2016-07-29 09:02:19
original
1012 Les gens l'ont consulté

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

<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>
Copier après la connexion

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>
Copier après la connexion

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

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal