繼承舊專案、無文檔、類別檔案分散,需要快速找出某函數/方法定義在哪個檔案、第幾行。
<?php
/**
* 輸出函數或方法的定義位置
* @param string|array $func 函數名 或 [類別名, 方法名]
*/
function function_dump($func) {
try {
if (is_array($func)) {
$ref = new ReflectionMethod($func[0], $func[1]);
$name = $func[0] . '::' . $func[1];
} else {
$ref = new ReflectionFunction($func);
$name = $func;
}
} catch (ReflectionException $e) {
echo "找不到: " . $e->getMessage() . "\n";
return;
}
$file = $ref->getFileName();
$start = $ref->getStartLine();
$end = $ref->getEndLine();
echo "function $name defined by $file($start - $end)\n";
}
// 使用範例
function_dump('get_affiliate'); // 一般函數
function_dump(['UserService', 'getById']); // 類別方法
?>
function get_affiliate defined by D:\WWW\admin\affiliate.php(232 - 238)
function UserService::getById defined by D:\WWW\service\UserService.php(45 - 62)
function open_in_editor($func) {
try {
$ref = is_array($func)
? new ReflectionMethod($func[0], $func[1])
: new ReflectionFunction($func);
$file = $ref->getFileName();
$line = $ref->getStartLine();
// Windows: code --goto file:line (VS Code)
// Mac/Linux: 同上 或用 sublime_text, phpstorm 等 protocol
exec("code --goto \"$file:$line\"");
} catch (ReflectionException $e) {
echo $e->getMessage();
}
}
反射操作較慢,不要在高頻生產路徑使用,僅限開發/除錯/初始化階段。