除錯開源專案時,常需快速定位某個函數或類別方法的原始碼位置。若無 IDE 自動跳轉,可用 PHP 內建的 ReflectionFunction 與 ReflectionMethod 實作工具函式。
<?php
function a() {}
class b {
public function f() {}
}
function function_dump($funcname) {
try {
if (is_array($funcname)) {
// 類別方法:array('類別名', '方法名') 或 array($object, '方法名')
$func = new ReflectionMethod($funcname[0], $funcname[1]);
$funcname = $funcname[1];
} else {
// 一般函數
$func = new ReflectionFunction($funcname);
}
} catch (ReflectionException $e) {
echo $e->getMessage();
return;
}
$start = $func->getStartLine() - 1; // 起始行(含左大括號前一行)
$end = $func->getEndLine() - 1; // 結束行
$file = $func->getFileName();
echo "function $funcname defined by $file($start - $end)\n";
}
// 測試
function_dump('a'); // 一般函數
function_dump(array('b', 'f')); // 靜態類別方法
$b = new b();
function_dump(array($b, 'f')); // 實例方法
?>
function a defined by /path/to/script.php(3 - 5) function f defined by /path/to/script.php(8 - 10) function f defined by /path/to/script.php(8 - 10)
ReflectionFunction::__construct():建立函數反射物件。ReflectionMethod::__construct():建立類別方法反射物件。getStartLine() / getEndLine():取得定義起迄行號。getFileName():取得檔案完整路徑。只需幾行程式碼,即可在無 IDE 環境下快速定位函數定義,大幅提升除錯效率。