2024 年日本 PHP 研討會

ReflectionFunction::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionFunction::__construct建構 ReflectionFunction 物件

說明

public ReflectionFunction::__construct(Closure|字串 $function)

建構一個 ReflectionFunction 物件。

參數

function

要反射的函式名稱或是一個 閉包 (closure)

錯誤/例外

如果 function 參數不包含有效的函式,則會拋出 ReflectionException

範例

範例 #1 ReflectionFunction::__construct() 範例

<?php
/**
* 一個簡單的計數器
*
* @return int
*/
function counter1()
{
static
$c = 0;
return ++
$c;
}

/**
* 另一個簡單的計數器
*
* @return int
*/
$counter2 = function()
{
static
$d = 0;
return ++
$d;

};

function
dumpReflectionFunction($func)
{
// 顯示基本資訊
printf(
"\n\n===> %s 函式 '%s'\n".
" 宣告於 %s\n".
" 第 %d 行到第 %d 行\n",
$func->isInternal() ? '內建' : '使用者定義',
$func->getName(),
$func->getFileName(),
$func->getStartLine(),
$func->getEndline()
);

// 顯示文件註釋
printf("---> 文件註釋:\n %s\n", var_export($func->getDocComment(), 1));

// 顯示靜態變數 (如果有的話)
if ($statics = $func->getStaticVariables())
{
printf("---> 靜態變數: %s\n", var_export($statics, 1));
}
}

// 建立 ReflectionFunction 類別的實例
dumpReflectionFunction(new ReflectionFunction('counter1'));
dumpReflectionFunction(new ReflectionFunction($counter2));
?>

上述範例的輸出會類似於

===> The user-defined function 'counter1'
     declared in Z:\reflectcounter.php
     lines 7 to 11
---> Documentation:
 '/**
 * A simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'c' => 0,
)


===> The user-defined function '{closure}'
     declared in Z:\reflectcounter.php
     lines 18 to 23
---> Documentation:
 '/**
 * Another simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'd' => 0,
)

另請參閱

新增註解

使用者提供的註解

此頁面沒有使用者提供的註解。
To Top