Search code examples
phpclassreferenceclonecopy-initialization

Difference between $a=&$b , $a = $b and $a= clone $b in PHP OOP


What is the difference between $a = &$b, $a = $b and $b = clone $a in PHP OOP? $a is an instance of a class.


Solution

  • // $a is a reference of $b, if $a changes, so does $b.    
    $a = &$b; 
    
    // assign $b to $a, the most basic assign.
    $a = $b; 
    
    // This is for object clone. Assign a copy of object `$b` to `$a`. 
    // Without clone, $a and $b has same object id, which means they are pointing to same object.
    $a = clone $b; 
    

    And check more info with References, Object Cloning.