2024 日本 PHP 研討會

ReflectionClass::getMethod

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getMethod取得類別方法的 ReflectionMethod

說明

public ReflectionClass::getMethod(string $name): ReflectionMethod

取得類別方法的 ReflectionMethod

參數

名稱

要反映的方法名稱。

回傳值

一個 ReflectionMethod 物件。

錯誤/例外

如果方法不存在,則會拋出 ReflectionException 例外。

範例

範例 #1 ReflectionClass::getMethod() 的基本用法

<?php
$class
= new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>

以上範例將輸出

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}

參見

新增註記

使用者貢獻的註記 2 則註記

Jarrod Nettles
13 年前
如果您需要取得方法中參數的類型提示,請使用以下程式碼。

<?php

//指定目標類別
$reflector = new ReflectionClass('MyClass');

//取得方法的參數
$parameters = $reflector->getMethod('FireCannon')->getParameters();

//迴圈處理每個參數並取得其類型
foreach($parameters as $param)
{
//在呼叫 getClass() 之前,該類別必須已定義!
echo $param->getClass()->name;
}

?>
sagittaracc at gmail dot com
3 年前
如果您需要取得方法的程式碼主體,請使用此擴充套件 (https://github.com/sagittaracc/reflection)

namespace sagittaracc\classes;

class Test
{
public function method()
{
if (true) {
return 'this method';
}

return 'never goes here';
}
}

$reflection = new ReflectionClass(Test::class);
$method = $reflection->getMethod('method');
echo $method->body; // if (true) { return 'this method'; } return 'never goes here';
To Top