PHP - 類/物件 get_declared_interfaces() 函式



PHP 類/物件 **get_declared_interfaces()** 函式用於返回一個數組,其中列出了程式中建立的所有介面的名稱。此函式對於除錯和動態類處理非常有用。

語法

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

array get_declared_interfaces()

引數

此 **get_declared_interfaces()** 函式沒有引數。

返回值

此函式返回當前指令碼中已宣告介面的名稱陣列。

PHP 版本

**get_declared_interfaces()** 函式首次引入於 PHP 5 核心版本中,在 PHP 7 和 PHP 8 中也能輕鬆使用。

示例 1

在下面的示例中,我們使用 PHP 類/物件 **get_declared_interfaces()** 函式來獲取內建介面的陣列。

<?php
   print_r(get_declared_interfaces());
?> 

輸出

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

Array ( 
   [0] => Traversable
   [1] => IteratorAggregate
   [2] => Iterator
   [3] => ArrayAccess
   [4] => reflector
   [5] => RecursiveIterator
   [6] => SeekableIterator
)

示例 2

在此示例中,我們將建立一個介面,然後使用 **get_declared_interfaces()** 函式獲取所有已宣告介面的列表。

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

   // Get interfaces details
   $interfaces = get_declared_interfaces();

   // Display the result
   print_r($interfaces);
?>

輸出

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

Array
(
   [0] => Traversable
   [1] => IteratorAggregate
   [2] => Iterator
   [3] => Serializable
   [4] => ArrayAccess
   [5] => Countable
   [6] => Stringable
   [7] => Throwable
   [8] => UnitEnum
   [9] => BackedEnum
   . 
   . 
   .
   [27] => Ds\Sequence
   [28] => MyInterface
)

示例 3

在下面的 PHP 程式碼中,我們將宣告多個介面,然後使用 **get_declared_interfaces()** 函式檢視它如何處理所有介面。

<?php
   // Create interfaces here
   interface FirstInterface {}
   interface SecondInterface {}
   
   // Get details of interfaces
   $interfaces = get_declared_interfaces();
   
   // Display the result
   print_r($interfaces);
?> 

輸出

這將生成以下輸出:

Array
(
   [0] => Traversable
   [1] => IteratorAggregate
   [2] => Iterator
   [3] => Serializable
   [4] => ArrayAccess
   [5] => Countable
   [6] => Stringable
   [7] => Throwable
   [8] => UnitEnum
   [9] => BackedEnum
   . 
   . 
   .
   [27] => Ds\Sequence
   [28] => FirstInterface
   [29] => SecondInterface
)

示例 4

此示例表明,即使類實現了介面,**get_declared_interfaces()** 也會成功列出該介面。

<?php
   // Create interfaces here
   interface MyInterface {}
   
   // Create a class and implement the interface
   class MyClass implements MyInterface {}
   
   // Get details of interfaces
   $interfaces = get_declared_interfaces();
   
   // Display the result
   print_r($interfaces);
?> 

輸出

這將建立以下輸出:

Array
(
   [0] => Traversable
   [1] => IteratorAggregate
   [2] => Iterator
   [3] => Serializable
   [4] => ArrayAccess
   [5] => Countable
   [6] => Stringable
   [7] => Throwable
   [8] => UnitEnum
   [9] => BackedEnum
   . 
   . 
   .
   [27] => Ds\Sequence
   [28] => MyInterface
)
php_function_reference.htm
廣告