PHP比較對象

WBOY
發布: 2023-08-30 15:30:02
轉載
1325 人瀏覽過

PHP比較對象

簡介

PHP 有一個比較運算子 ==,使用它可以執行兩個 objecs 變數的簡單比較。如果兩者屬於同一類別且對應屬性的值相同,則傳回 true。

PHP 的 === 運算子比較兩個物件變量,當且僅當它們引用時傳回true相同類別的相同實例

我們使用以下兩個類別來比較物件與這些運算子

範例

<?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;
   }
}
?>
登入後複製

同一類別的兩個物件

範例

$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);
登入後複製

輸出

two objects of same class
using == operator : bool(true)
using === operator : bool(false)
登入後複製

同一物件的兩個引用

範例

$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);
登入後複製

輸出

two references of same object
using == operator : bool(true)
using === operator : bool(true)
登入後複製

兩個不同類別的物件

範例

$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 shows following result

two objects of different classes
using == operator : bool(false)
using === operator : bool(false)
登入後複製

以上是PHP比較對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!