類別和介面共用相同的命名空間!
class k{}
interface k {} // 致命錯誤:無法重新宣告類別 k
(PHP 5 >= 5.0.2, PHP 7, PHP 8)
interface_exists — 檢查介面是否已定義
範例 #1 interface_exists() 範例
<?php
// 在嘗試使用介面前,先檢查介面是否存在
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface
{
// 方法
}
}
?>
關於命名空間的一點小註記,對某些人來說可能很明顯,但對我來說卻並非如此。
雖然當語句與介面/類別宣告 MyInterface 位於相同的命名空間時,您可以使用以下語句...
<?php
$foo instanceof MyInterface
?>
使用 interface_exists 或 class_exists 函式時,您必須輸入完整的命名空間介面名稱,如下所示(即使函式呼叫來自相同的命名空間)。
<?php
interface_exists(__NAMESPACE__ . '\MyInterface', false);
?>
據我所知,interface_exists() 是在 5.0.2 版本中新增的。在 5.0.0 和 5.0.1 中,當查詢現有的介面時,class_exists() 會返回 TRUE。從 5.0.2 開始,class_exists() 不再這樣做了。
如果您想檢查已包含的介面,並且您已經註冊了 spl 自動載入器,它將會崩潰。因為自動載入器會嘗試載入 `string`,而它不在乎它是類別還是其他東西。
我找到了幾種方法
1 - 移除 AL 註冊 - -> 檢查介面 - -> 註冊自動載入器
2 - $ifaces = array_flip(get_declared_interfaces());
if($ifaces["MyIface"]) // 空的 // isset 。
介面並非不好,您可以透過函式/變數/常數驗證,建構正確的系統架構。
它們也適合儲存變數 <?php
ROOT::THEMES ; ROOT::LOC ; ?>。 比 Define 快得多,但您不能在裡面放置演算法,只能放置完整的字串 / __file__ / 等等。