PHP 反射 API (ReflectionClass) 能在執行期檢視類別結構。常見用途:框架自動載入除錯、插件系統掃描、程式碼分析工具。本文示範如何取得類別檔案路徑與方法定義位置。
<?php
class ServiceContainer {
public function loadConfig(string $path): array { /* ... */ }
}
// 1. 建立 ReflectionClass 實例
$reflector = new ReflectionClass(ServiceContainer::class);
// 或從實例
$obj = new ServiceContainer();
$reflector = new ReflectionClass($obj);
// 2. 取得檔案路徑 (絕對路徑)
$filePath = $reflector->getFileName();
echo $filePath; // /var/www/project/src/ServiceContainer.php
// 3. 取得起始/結束行號
echo "起始行: {$reflector->getStartLine()}"; // 如 5
echo "結束行: {$reflector->getEndLine()}"; // 如 45
?>
<?php
$methodName = 'loadConfig';
// 取得方法反射器
$method = $reflector->getMethod($methodName);
// 方法所在類別 (可能繼承自父類別)
$declaringClass = $method->getDeclaringClass();
echo "定義於類別: {$declaringClass->getName()}
";
// 方法檔案路徑與行號
echo "檔案: {$declaringClass->getFileName()}
";
echo "起始行: {$method->getStartLine()}
";
echo "結束行: {$method->getEndLine()}
";
// 取得方法原始碼片段 (需讀取檔案)
$source = file($declaringClass->getFileName());
$methodCode = implode('', array_slice($source, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
highlight_string($methodCode);
?>
<?php
function scanModules(string $namespace, string $basePath): array {
$modules = [];
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($basePath)
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$relative = str_replace($basePath . '/', '', $file->getPathname());
$className = $namespace . '\\' . str_replace(['/', '.php'], ['\\', ''], $relative);
if (class_exists($className)) {
$rc = new ReflectionClass($className);
// 過濾:只掃描實作特定介面的類別
if ($rc->implementsInterface(ModuleInterface::class)) {
$modules[] = [
'class' => $className,
'file' => $rc->getFileName(),
'line' => $rc->getStartLine(),
];
}
}
}
}
return $modules;
}
?>
getFileName() 回傳 false 表示內建類別 (如 DateTime、PDO) 或動態建立的類別 (eval())。ReflectionClass::getAttributes() 可讀取屬性 (Attributes),替代註解解析。