Home > Backend Development > PHP Tutorial > PHP clone clone

PHP clone clone

WBOY
Release: 2016-07-29 09:02:19
Original
1010 people have browsed it

Shallow cloning: only clone non-object non-resource data in the object, that is, the attributes in the object store the object type, then there will be incomplete cloning

<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>
Copy after login

PHP clone clone

Deep cloning: all attribute data of an object To completely copy, you need to use the magic method __clone(), and implement deep cloning in it

<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>
Copy after login

PHP clone clone

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above introduces PHP clone, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template