How to clone and compare objects

How to clone an object

The syntax

      clone $objectName
      

An object to clone

      $brass = new Category(4, 'Brass'); 
      $trumpet = new Product($brass, 'Getzen', 'Getzen 700SP Trumpet', 999.95);
      

Create a second reference to an object

      $trombone = $trumpet; 
      $trombone->setPrice(699.95);
      

Create a clone of an object

      $trombone = clone $trumpet; 
      $trombone->setPrice(899.95);
      

The copies are shallow copies

      $trombone->getCategory()->setName('Orchestral Brass'); 
      echo $trumpet->getCategory()->getName(); // Displays 'Orchestral Brass'
      

How to compare two objects

Use the equality (==) operator

      $result_1 = ($trumpet == $trombone); // $result_1 is FALSE
      
      $flugelhorn = clone $trumpet; 
      $result_2 = ($trumpet == $flugelhorn); // $result_2 is TRUE
      

Use the identity (===) operator

       $result_3 = ($trumpet === $flugelhorn); // $result_3 is FALSE 
       
       $trumpet_2 = $trumpet;
       $result_4 = ($trumpet === $trumpet_2); // $result_4 is TRUE 
       
       $result_5 = ($trumpet->getCategory() === $trombone->getCategory()); // $result_5 is TRUE
      

Description

Back