PHP - 類/物件 get_class_methods() 函式



PHP 類/物件 get_class_methods() 函式用於以陣列的形式返回特定類或物件的方法名稱。此函式對於提供可用於特定物件或類的所有方法的列表非常有用。

語法

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

array get_class_methods( object|string $object_or_class )

引數

此函式接受 $object_or_class 引數,它是類名或物件例項。

返回值

get_class_methods() 函式返回為類名指定的類定義的方法名稱陣列。如果發生錯誤,則返回 NULL。

PHP 版本

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

示例 1

首先,我們將向您展示 PHP 類/物件 get_class_methods() 函式的基本示例,以從簡單類中獲取方法。該函式僅返回公共函式,因此 method3 將不會包含在內,因為它是一個私有方法。

<?php
   // Declare MyClass here
   class MyClass {
      public function method1() {}
      public function method2() {}
      private function method3() {}
   }
    
   $methods = get_class_methods('MyClass');
   print_r($methods);
?>

輸出

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

Array
(
    [0] => method1
    [1] => method2
)

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 get_class_methods() 函式並從物件例項中獲取方法。

<?php
   // Declare MyClass here
   class MyClass {
      public function signUp() {}
      public function signIn() {}
   }
    
   $obj = new MyClass();
   $methods = get_class_methods($obj);
   print_r($methods);
?> 

輸出

這將生成以下輸出:

Array
(
  [0] => signUp
  [1] => signIn
)

示例 3

此示例演示了 get_class_methods() 函式的工作原理,並從父類繼承方法。

<?php
   // Declare ParentClass here
   class ParentClass {
      public function parentMethod() {}
   }
    
   // Declare ChildClass here
   class ChildClass extends ParentClass {
     public function childMethod() {}
   }
    
   $methods = get_class_methods('ChildClass');
   print_r($methods);
?> 

輸出

這將建立以下輸出:

Array
(
    [0] => childMethod
    [1] => parentMethod
)

示例 4

此程式碼建立一個名為 Myclass 的類,其中包含一個建構函式和兩個方法(function1 和 function2)。它使用 get_class_methods() 獲取並列印類中所有方法的名稱。

<?php
  // Declare Myclass here
  class Myclass {

      // constructor
      function __construct()
      {
         return(true);
      }

      // Declare function 1
      function function1()
      {
         return(true);
      }

      // Declare function 2
      function function2()
      {
         return(true);
      }
   }

   $class_methods = get_class_methods(new myclass());

   foreach ($class_methods as $method_name) {
      echo "$method_name\n";
   }
?> 

輸出

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

__construct
myfunc1
myfunc2
php_function_reference.htm
廣告