2024 年 PHP 日本研討會

class_implements

(PHP 5, PHP 7, PHP 8)

class_implements 傳回指定類別或介面所實作的介面

說明

class_implements(物件|字串 $object_or_class, 布林 $autoload = true): 陣列|false

此函式會傳回一個陣列,其中包含指定 object_or_class 及其父類別所實作的介面名稱。

參數

object_or_class

物件(類別實例)或字串(類別或介面名稱)。

autoload

是否在尚未載入時進行 自動載入

回傳值

成功時返回一個陣列,如果指定的類別不存在則返回 false

範例

範例 #1 class_implements() 範例

<?php

interface foo { }
class
bar implements foo {}

print_r(class_implements(new bar));

// 也可以將參數指定為字串
print_r(class_implements('bar'));

spl_autoload_register();

// 使用自動載入來載入 'not_loaded' 類別
print_r(class_implements('not_loaded', true));

?>

上述範例的輸出結果類似於

Array
(
    [foo] => foo
)
Array
(
    [foo] => foo
)
Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

注意事項

注意: 要檢查物件是否實作了介面,應該使用 instanceofis_a() 函式。

參見

新增註釋

使用者貢獻的註釋 3 則註釋

ludvig dot ericson at gmail dot nospam dot com
19 年前
提示
<?php
in_array
("your-interface", class_implements($object_or_class_name));
?>
會檢查 'your-interface' 是否為已實作的介面之一。
請注意,您可以使用類似的方法來確保類別只實作該介面(無論您為何需要這樣做)。
<?php
array("your-interface") == class_implements($object_or_class_name);
?>

我使用第一種技術來檢查模組是否已實作正確的介面,否則會擲出例外。
a dot panek at brainsware dot org
11 年前
使用無法載入的類別名稱或非物件呼叫 class_implements 會導致警告

<?php
// 警告:class_implements():類別 abc 不存在且無法載入 /home/a.panek/Projects/sauce/lib/Sauce/functions.php,第 196 行

$interfaces = class_implements('abc');
?>

這並沒有被記錄在文件中,而且應該只會回傳 FALSE,如同上述文件所述。
trollll23 at yahoo dot com
19 年前
幸運的是,它也會以相反的順序印出父介面,因此迭代搜尋可以正常運作。

<?php

interface InterfaceA { }

interface
InterfaceB extends InterfaceA { }

class
MyClass implements InterfaceB { }

print_r(class_implements(new MyClass()));

?>

印出

陣列
(
[InterfaceB] => InterfaceB
[InterfaceA] => InterfaceA
)
To Top