Home  >  Article  >  Backend Development  >  PHP comparison objects

PHP comparison objects

WBOY
WBOYforward
2023-08-30 15:29:061289browse

PHP comparison objects

Introduction

PHP has a comparison operator ==, which can be used to perform a simple comparison of two objecs variables. Returns true if both belong to the same class and the values ​​of the corresponding properties are the same.

PHP’s === Operator compares two object variables and returns true if and only if they refer to the same instance of the same class

We use the following two Class to compare objects with these operators

Example

<?php
class test1{
   private $x;
   private $y;
   function __construct($arg1, $arg2){
      $this->x=$arg1;
      $this->y=$arg2;
   }
}
class test2{
   private $x;
   private $y;
   function __construct($arg1, $arg2){
      $this->x=$arg1;
      $this->y=$arg2;
   }
}
?>

Two objects of the same class

Example

$a=new test1(10,20);
$b=new test1(10,20);
echo "two objects of same class";
echo "using == operator : ";
var_dump($a==$b);
echo "using === operator : ";
var_dump($a===$b);

Output

two objects of same class
using == operator : bool(true)
using === operator : bool(false)

Two references to the same object

Example

$a=new test1(10,20);
$c=$a;
echo "two references of same object";
echo "using == operator : ";
var_dump($a==$c);
echo "using === operator : ";
var_dump($a===$c);

Output

two references of same object
using == operator : bool(true)
using === operator : bool(true)

Two objects of different classes

Example

$a=new test1(10,20);
$d=new test2(10,20);
echo "two objects of different classes";
echo "using == operator : ";
var_dump($a==$d);
echo "using === operator : ";
var_dump($a===$d);

Output

Output shows following result

two objects of different classes
using == operator : bool(false)
using === operator : bool(false)

The above is the detailed content of PHP comparison objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete