PHP - 類/物件 interface_exists() 函式



PHP 類/物件 interface_exists() 函式用於檢查給定的介面是否已定義。如果介面存在則返回 true,否則返回 false。此函式用於在程式碼中使用介面之前檢查介面是否存在。

語法

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

bool interface_exists(string $interface, bool $autoload = true)

引數

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

  • $interface - 要檢查的介面名稱,應為字串。

  • $autoload - 布林值,定義是否應自動載入介面,如果未指定則預設為 true。

返回值

interface_exists() 函式如果 interface_name 指定的介面已定義則返回 TRUE,否則返回 FALSE。

PHP 版本

interface_exists() 函式首次出現在核心 PHP 5.0.2 中,在 PHP 7 和 PHP 8 中繼續輕鬆執行。

示例 1

首先,我們將向您展示 PHP 類/物件 interface_exists() 函式的基本示例,以檢查名為 MyInterface 的介面是否存在。

<?php
   // Declare interface here
   interface MyInterface {}

   // Check using interface_exists method
   $result = interface_exists('MyInterface');

   //Display the result
   var_dump($result); 
?>

輸出

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

bool(true)

示例 2

在此示例中,我們將看到如果介面不存在,使用 interface_exists() 方法檢查介面時會發生什麼。

<?php
   // Check for nonexistent interface
   $result = interface_exists('NonExistentInterface');

   //Display the result
   var_dump($result); 
?> 

輸出

這將生成以下輸出:

bool(false)

示例 3

在此,函式檢查介面,並且預設情況下啟用自動載入。

<?php
   spl_autoload_register(function ($interface) {
      if ($interface === 'AutoLoadedInterface') {
          eval('interface AutoLoadedInterface {}');
      }
  });
  
  $result = interface_exists('AutoLoadedInterface');
  var_dump($result); 
?> 

輸出

這將建立以下輸出:

bool(true)

示例 4

此示例在停用自動載入時查詢介面,這意味著如果尚未定義,則不會載入它。

<?php
   spl_autoload_register(function ($interface) {
      if ($interface === 'AutoLoadedInterface') {
          eval('interface AutoLoadedInterface {}');
      }
  });
  
  $result = interface_exists('AutoLoadedInterface', false);
  var_dump($result); 
?> 

輸出

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

bool(false)
php_function_reference.htm
廣告