菜单

Detailed explanation of shallow replication and deep replication of PHP objects

2017年11月22日 - PHPer

Detailed explanation of shallow replication and deep replication of PHP objects

Recently noticed difference object of this problem in ~~PHP and clone’at t’ prototype model

Instance code:

/ / aggregation

Class ObjA {

Public $num = 0;

Public $objB; / / included objects

Function __construct () {

$this-> objB = new ObjB ();

}

Only to achieve the following method to realize / deep copy polymerization ability

/*function __clone () {

$this-> objB = clone $this-> objB;

}*/

}

Class ObjB {

$num2 public = 0;

}

The prototype object / /

$objA = new ObjA ();

Copy the object (‘=’ / / copy quote)

$objA2 = $objA;

$objA2-> num = 2;

With the change of $objA-&gt / / $objA2-> num; num changes

Print_r ($objA-> num.'< br/> ‘); / / the 2

Print_r ($objA2-> num.'< br/> ‘); / / the 2

Copy the object (“/ / clone’keyword clone)

$objA3 = clone $objA;

$objA3-> num = 4;

With the change of $objA-&gt / / $objA3-> num; num did not change.

Print_r ($objA-> num.'< br/> ‘); / / the 2

Print_r ($objA3-> num.'< br/> ‘); / / the 4

But the clone (object / / is the aggregation of objects contained in) contains other objects when the copy is a reference (objB)

$objA3-> objB-> num2 = 7;

Print_r ($objA3-> objB-> num2.'< br/> ‘); / / the result is 7

Print_r ($objA-> objB-> num2.'< br/> ‘); / / the result is 7< /pre>

发表评论

电子邮件地址不会被公开。