: This article mainly introduces php object-oriented Clone and Serialization. For more information about PHP tutorials, see. There are three solutions for copying objects:
1. Copy $ a = $ B directly.
This is a shallow copy. when $ a is changed, $ B also changes because they point to the same heap zone.
2. clone replication $ a = clone $ B
This kind of copy seems to be a deep Copy. when $ a changes, $ B will not change. at the same time, PHP provides the magic method _ Clone () to customize Clone replication, you can customize the attributes that do not want to be copied or that need to be changed during the replication process in the _ clone () method.
However, this replication method has a defect. it should be noted that if the type of an attribute in the class is another class, will this attribute be deeply copied during Clone, of course, this defect can be compensated by the magic method _ clone. in the _ clone () method, a new class is provided for this attribute.
Class test {private $ name; private $ sex; private $ demo; public function _ construct ($ name, $ sex, $ demo) {$ this-> name = $ name; $ this-> sex = $ sex; $ this-> demo = $ demo;} public function _ set ($ key, $ value) {$ this-> {$ key} = $ value;} public function _ get ($ key) {return $ this-> {$ key };} public function _ clone () {$ this-> name = 'null'; // You can customize clone here }}
class demo{private $name;public function __construct($name='demo01'){$this->name = $name;}public function __set($key,$value){$this->{$key} = $value;}public function __get($key){return $this->{$key};}}
$ T = new test ('A', 'BB ', new demo ('d01'); $ d = clone $ t; // $ d-> name = 'Nihao'; $ d-> demo-> name = 'd02'; var_dump ($ t ); // result $ t-> demo-> name d02Use clone to compensate
public function __clone(){$this->name='null';$this->demo = new demo('init');}
3. serialized replication
$b = unserialize(serialize($t));
In this way, you do not need to use the clone magic method to achieve deep copy of the reference type in the attribute.
The above introduces php object-oriented Clone and serialization, including some content, and hope to be helpful to friends who are interested in PHP tutorials.