Home > Article > Backend Development > php object-oriented Clone and serialization
There are three options for copying objects:
1, direct copy $a = $b
This is a shallow copy, when $a is changed, $b will also change, because They point to the same heap area
2, clone copy $a = clone $b
This copy seems to be a deep copy. When $a changes, $b will not follow. At the same time, PHP provides the magic method __Clone() to customize Clone replication. Which attributes do not want to be copied and what changes are needed during the replication process can be customized in the __clone() method.
However, this copying method has a flaw. It should be noted that if the type of a certain attribute in the class is another class, then this attribute will not be deep copied during Clone. , isn’t it embarrassing? Of course, this shortcoming can be made up for by the magic method __clone. Just create a new new class for this attribute in the __clone() method.
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'; //这里可以自定义clone } }
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('aa', 'bb',new demo('d01')); $d = clone $t; //$d->name='nihao'; $d->demo->name = 'd02'; var_dump($t); //结果 $t->demo->name d02Use clone to make up
public function __clone(){ $this->name='null'; $this->demo = new demo('init'); }3, serialized copy
$b = unserialize(serialize($t));This way you can implement attributes without using the clone magic method A deep copy of the reference type was made.
The above introduces PHP object-oriented Clone and serialization, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.