Saturday 29 May 2021

Php: How to compare two objects?

There are two ways to compare two objects in Php.

 

Using == operator

== operator considers objects to be equal if they satisfy any of the following conditions.

a.   Both references point to the same instance

b.   Instances with matching properties and values.

 

This will return false, if objects are of different type (or) do not have same properties with same values.

 

objects_comparison_demo.php

#!/usr/bin/php

<?php

    class Employee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

   
    class MyEmployee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

    $emp1 = new Employee(1, 'Krishna');
    $emp1_reference = $emp1;
    $emp2 = new Employee(1, 'Krishna');
    $emp3 = new Employee(2, 'Shankar');
    $my_emp = new MyEmployee(1, 'Krishna');

    echo '$emp1==$emp1_reference : '. (($emp1==$emp1_reference)?'T':'F') . "\n";
    echo '$emp1==$emp2 : '. (($emp1==$emp2)?'T':'F') . "\n";
    echo '$emp1==$emp3 : '. (($emp1==$emp3)?'T':'F') . "\n";
    echo '$emp1==$my_emp : '. (($emp1==$my_emp)?'T':'F') . "\n";



?>

 

Output

$./objects_comparison_demo.php 

$emp1==$emp1_reference : T
$emp1==$emp2 : T
$emp1==$emp3 : F
$emp1==$my_emp : F

 

Using === operator

=== operator considers objects to be equal if both the references point to the same instance.

 

objects_strict_comparison_demo.php

 

#!/usr/bin/php

<?php

    class Employee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

   
    class MyEmployee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

    $emp1 = new Employee(1, 'Krishna');
    $emp1_reference = $emp1;
    $emp2 = new Employee(1, 'Krishna');
    $emp3 = new Employee(2, 'Shankar');
    $my_emp = new MyEmployee(1, 'Krishna');

    echo '$emp1===$emp1_reference : '. (($emp1===$emp1_reference)?'T':'F') . "\n";
    echo '$emp1===$emp2 : '. (($emp1===$emp2)?'T':'F') . "\n";
    echo '$emp1===$emp3 : '. (($emp1===$emp3)?'T':'F') . "\n";
    echo '$emp1===$my_emp : '. (($emp1===$my_emp)?'T':'F') . "\n";



?>

 

Output

$./objects_strict_comparison_demo.php 

$emp1===$emp1_reference : T
$emp1===$emp2 : F
$emp1===$emp3 : F
$emp1===$my_emp : F

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment