PHP 的 Reflection API 可在執行時檢查類別、介面、方法、屬性等結構資訊。常見用途包含:框架路由掃描、註解解析、除錯工具、程式碼產生器等。本文示範如何取得類別/方法的定義檔案路徑、起始行號與結束行號。
getStartLine(); // 方法定義起始行
$endLine = $method->getEndLine(); // 方法定義結束行
$fileName = $method->getFileName(); // 所在檔案完整路徑
echo "檔案: $fileName\n";
echo "行號範圍: $startLine - $endLine\n";
?>
getMessage() . "\n";
return;
}
$name = is_array($callable) ? $callable[1] : $reflector->getName();
$file = $reflector->getFileName();
$start = $reflector->getStartLine();
$end = $reflector->getEndLine();
echo "函數/方法 [$name] 定義於: $file (第 $start - $end 行)\n";
}
// 使用範例
function demoFunc() { /* ... */ }
class DemoClass { public function demoMethod() { /* ... */ } }
dumpFunctionLocation('demoFunc');
dumpFunctionLocation(['DemoClass', 'demoMethod']);
dumpFunctionLocation([new DemoClass(), 'demoMethod']);
?>
getFileName();
$start = $rm->getStartLine() - 1; // 轉 0-based 索引
$end = $rm->getEndLine();
$lines = file($file);
return implode('', array_slice($lines, $start, $end - $start));
}
// 輸出完整方法原始碼
echo getMethodSource('UnifiedOrder_pub', 'getPrepayId');
?>
| 方法 | 說明 |
|---|---|
getName() | 方法名稱 |
getDeclaringClass() | 宣告該方法的類別 (ReflectionClass) |
getFileName() | 定義檔案路徑 |
getStartLine() / getEndLine() | 起始/結束行號 |
getParameters() | 參數列表 (ReflectionParameter[]) |
getReturnType() | 回傳型別 (PHP 7.0+) |
isPublic() / isPrivate() / isProtected() | 可見性檢查 |
isStatic() / isAbstract() / isFinal() | 修飾詞檢查 |
invoke($obj, ...$args) / invokeArgs($obj, $args) | 動態呼叫方法 |
opcache 加速檔案載入與編譯。