PHP Conference Japan 2024

interface_exists

(PHP 5 >= 5.0.2, PHP 7, PHP 8)

interface_exists檢查介面是否已定義

描述

interface_exists(字串 $interface, 布林值 $autoload = true): 布林值

檢查指定的介面是否已定義。

參數

interface

介面名稱

autoload

如果尚未載入,是否要自動載入

回傳值

如果 interface 指定的介面已定義,則返回 true,否則返回 false

範例

範例 #1 interface_exists() 範例

<?php
// 在嘗試使用介面前,先檢查介面是否存在
if (interface_exists('MyInterface')) {
class
MyClass implements MyInterface
{
// 方法
}
}

?>

參見

新增註記

使用者貢獻的註記 4 筆註記

6
CoR
9 年前
類別和介面共用相同的命名空間!

class k{}

interface k {} // 致命錯誤:無法重新宣告類別 k
4
nils dot rocine at gmail dot com
13 年前
關於命名空間的一點小註記,對某些人來說可能很明顯,但對我來說卻並非如此。

雖然當語句與介面/類別宣告 MyInterface 位於相同的命名空間時,您可以使用以下語句...
<?php
$foo
instanceof MyInterface
?>

使用 interface_exists 或 class_exists 函式時,您必須輸入完整的命名空間介面名稱,如下所示(即使函式呼叫來自相同的命名空間)。
<?php
interface_exists
(__NAMESPACE__ . '\MyInterface', false);
?>
4
andrey at php dot net
20 年前
據我所知,interface_exists() 是在 5.0.2 版本中新增的。在 5.0.0 和 5.0.1 中,當查詢現有的介面時,class_exists() 會返回 TRUE。從 5.0.2 開始,class_exists() 不再這樣做了。
1
maxim at inbox dot ru
12 年前
如果您想檢查已包含的介面,並且您已經註冊了 spl 自動載入器,它將會崩潰。因為自動載入器會嘗試載入 `string`,而它不在乎它是類別還是其他東西。
我找到了幾種方法
1 - 移除 AL 註冊 - -> 檢查介面 - -> 註冊自動載入器

2 - $ifaces = array_flip(get_declared_interfaces());
if($ifaces["MyIface"]) // 空的 // isset 。

介面並非不好,您可以透過函式/變數/常數驗證,建構正確的系統架構。
它們也適合儲存變數 <?php
ROOT
::THEMES ; ROOT::LOC ; ?>。 比 Define 快得多,但您不能在裡面放置演算法,只能放置完整的字串 / __file__ / 等等。
To Top