PHP comparison objects

WBOY
Release: 2023-08-30 15:30:02
forward
1324 people have browsed it

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;
   }
}
?>
Copy after login

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);
Copy after login

Output

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

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);
Copy after login

Output

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

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);
Copy after login

Output

Output shows following result

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

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

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!