PHP Comparison Objects


 

PHP Comparison Objects

In this current tutorial we will study about the various ways of comparing two objects. There are several ways are provided in PHP to compare two objects of class (same or different)like ==,=== etc operators are present to compare two objects.

In this current tutorial we will study about the various ways of comparing two objects. There are several ways are provided in PHP to compare two objects of class (same or different)like ==,=== etc operators are present to compare two objects.

Comparison of Objects:

There are several ways are provided in PHP to compare two objects of class (same or different).

There are mainly = =, = = = operators are used to compare two objects, and instance of operator can be used also.

The operator = =  checks the attributes and values of objects and returns true if the objects are of same class and has equal values.

The operator = = = checks two objects and returns true if both refers two the same object a class.

Instance of is an operator which is used to check whether an object is an instance of a class or not. Following examples will exemplify these operators:

Example:

<?php

class A{

public $one;

 }

class B{

public $two;

public function display(){

}

}

$obj1=new A();

$obj2=new B();

$obj3=new A();

$obj4=$obj1;

echo "<b>Comparison of two objects of same class</b>";

compareObjects($obj1,$obj3);

echo "<br/><b>Comparison of two objects of different class</b>";

compareObjects($obj1,$obj2);

echo "<br/><b>Comparison of two references of same object</b>";

compareObjects($obj1,$obj4);

function compareObjects($obj1,$obj2){

echo "<br/>Using = = operator";

echo "<br/>Objects are same: ".op1($obj1,$obj2);

echo "<br/>Using instanceof operator";

0

echo "<br/> Objects are same: ".instance($obj1,$obj2);

echo "<br/>Using = = = operator";

echo "<br/> Objects are same: ".op2($obj1,$obj2);

1

}

function op1($obj1,$obj2){

if($obj1==$obj2)return "true";

2

else return "false";

}

function instance($obj1,$obj2){

3

if(($obj1 instanceof A)&&($obj2 instanceof A)) return "true";

else return 'false';

}

4

function op2($obj1,$obj2){

if($obj1===$obj2)return "true";

else return "false";

5

}

?>

 

6

Output:

Comparison of two objects of same class
Using = = operator
Objects are same: true
Using instanceof operator
Objects are same: true
Using = = = operator
Objects are same: false
Comparison of two objects of different class
Using = = operator
Objects are same: false
Using instanceof operator
Objects are same: false
Using = = = operator
Objects are same: false
Comparison of two references of same object
Using = = operator
Objects are same: true
Using instanceof operator
Objects are same: true
Using = = = operator
Objects are same: true

Ads