PHP - 類/物件 get_declared_classes() 函式



PHP 類/物件 get_declared_classes() 函式用於返回一個數組,其中包含程式碼中所有類的名稱,無論是使用者定義的還是內建的。此函式對於檢視程式碼中可用的類非常有用。

語法

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

array get_declared_classes (void)

引數

此函式不接受任何引數。

返回值

get_declared_classes() 函式返回一個數組,其中包含當前指令碼中已宣告的類的名稱。

PHP 版本

get_declared_classes() 函式首次引入到 PHP 4 的核心版本中,並且在 PHP 5、PHP 7 和 PHP 8 中繼續輕鬆執行。

示例 1

以下是 PHP 類/物件 get_declared_classes() 函式的基本示例,用於獲取已宣告類的名稱陣列。

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

輸出

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

Array
(
   [0] => InternalIterator
   [1] => Exception
   .
   .
   .
   [245] => Ds\Set
   [246] => Ds\PriorityQueue
   [247] => Ds\Pair
)

示例 2

在下面的 PHP 程式碼中,我們將使用 get_declared_classes() 函式,並在定義了一些類之後列出所有已宣告的類。

<?php
   // Declare the classes
   class MyClass1 {}
   class MyClass2 {}
   
   $classes = get_declared_classes();
   print_r($classes);
?> 

輸出

這將生成以下輸出:

Array
(
  [0] => InternalIterator
  [1] => Exception
  .
  .
  .
  [248] => MyClass1
  [249] => MyClass2
)

示例 3

現在,以下程式碼演示瞭如何使用 get_declared_classes() 函式檢查指令碼中是否聲明瞭特定類。

<?php
   // Declare MyClass here
   class MyClass {}

   $classes = get_declared_classes();
   if (in_array('MyClass', $classes)) {
       echo "MyClass is declared.";
   } else {
       echo "MyClass is not declared.";
   }
?> 

輸出

這將建立以下輸出:

MyClass is declared.

示例 4

此示例顯示了在包含另一個定義了其他類的檔案後,get_declared_classes() 函式是如何工作的。

<?php
   include '/PHP/PhpProjects/other_file.php';

   $classes = get_declared_classes();
   print_r($classes);
?> 

以下是 other_file.php 檔案中編寫的程式碼:

<?php
   class OtherClass {}
?> 

輸出

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

Array
(
  [0] => InternalIterator
  [1] => Exception
  .
  .
  .
  [248] => OtherClass
)
php_function_reference.htm
廣告