Detailed Explanation of Shallow Copy and Deep Copy of PHP Object

  • 2021-08-10 07:09:59
  • OfStack

Detailed Explanation of Shallow Copy and Deep Copy of PHP Object

Recently, I noticed this problem when I looked at prototype pattern ~ ~ the difference between object '=' and 'clone' in PHP

Example code:


// Aggregation class  
class ObjA { 
  public $num = 0; 
  public $objB;// Objects contained  
  function __construct() { 
    $this->objB = new ObjB(); 
  } 
  // Aggregate classes only if the following methods are implemented   To achieve deep replication  
  /*function __clone() { 
    $this->objB = clone $this->objB; 
  }*/ 
} 
 
class ObjB { 
  public $num2 = 0; 
} 
 
// Prototype object  
$objA = new ObjA(); 
 
// Copy objects (' =' Copy Reference)  
$objA2 = $objA; 
$objA2->num = 2; 
// With $objA2->num Change of  $objA->num It has also changed  
print_r($objA->num.'<br/>');// The result is 2 
print_r($objA2->num.'<br/>');// The result is 2 
 
// Copy objects (' clone' Keyword cloning)  
$objA3 = clone $objA; 
$objA3->num = 4; 
// With $objA3->num Change of  $objA->num No change  
print_r($objA->num.'<br/>');// The result is 2 
print_r($objA3->num.'<br/>');// The result is 4 
// But clone Objects included when other objects are included in the object of (which is an aggregate class) ( objB ) Copies a reference  
$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> 

If you have any questions, please leave a message or go to this site community to exchange and discuss, thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: