PHP - 類/物件 property_exists() 函式



PHP 類/物件 property_exists() 函式是一個內建方法,用於檢查物件和類是否具有任何屬性。如果屬性已定義,則返回 true;如果未定義,則返回 false。此函式對於在訪問物件或類中的屬性之前檢查其是否存在非常有用。

語法

以下是 PHP 類/物件 property_exists() 函式的語法:

bool property_exists ( 
   object|string $object_or_class, 
   string $property 
   )

引數

以下是 property_exists() 函式的引數:

  • $object_or_class − 要測試其屬性的物件或類的名稱。

  • $property − 類中屬性的名稱。

返回值

如果屬性存在,則 property_exists() 函式返回 TRUE;如果屬性不存在,則返回 FALSE;如果發生錯誤,則返回 NULL。

PHP 版本

property_exists() 函式首次引入於核心 PHP 5.1.0,並且在 PHP 7 和 PHP 8 中都能輕鬆使用。

示例 1

首先,我們將向您展示 PHP 類/物件 property_exists() 函式的基本示例,以檢查簡單物件中是否存在屬性。

<?php
   // Define a class here
   class Car {
      public $make;
   }
  
   $car = new Car();
   $car->make = "Toyota";
  
   if (property_exists($car, 'make')) {
      echo "Property 'make' exists.";
   } else {
      echo "Property 'make' does not exist.";
   }
?>

輸出

以下是以下程式碼的結果:

Property 'make' exists.

示例 2

在下面的示例中,我們將使用 property_exists() 函式來檢查建立的類中是否存在屬性。因此,在這種情況下,它將返回 false。

<?php
   //Define a class here
   class Bike {
      public $model;
   }
  
   $bike = new Bike();
  
   if (property_exists($bike, 'color')) {
      echo "Property 'color' exists.";
   } else {
      echo "Property 'color' does not exist.";
   }
?> 

輸出

這將生成以下輸出:

Property 'color' does not exist.

示例 3

在這裡,property_exists() 函式用於使用類名稱作為字串來驗證類中的靜態屬性。

<?php
   // Define a class here
   class Plane {
      public static $type = "Jet";
   }

   if (property_exists('Plane', 'type')) {
      echo "Property 'type' exists in Plane class.";
   } else {
      echo "Property 'type' does not exist in Plane class.";
   }
?> 

輸出

這將建立以下輸出:

Property 'type' exists in Plane class.

示例 4

現在,我們將建立一個包含私有屬性的類,然後使用 property_exists() 方法檢查私有屬性是否存在。

<?php
   // Define a class here
   class Road {
      private $length = 50;
   }
  
   $road = new Road();
  
   if (property_exists($road, 'length')) {
      echo "Property 'length' exists in Road class.";
   } else {
      echo "Property 'length' does not exist in Road class.";
   }
?> 

輸出

以下是上述程式碼的輸出:

Property 'length' exists in Boat class.
php_function_reference.htm
廣告