萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 反射機制獲取類別檔案路徑

ReflectionClass 實戰:動態取得類別定義檔案位置

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())。
  • 反射操作有效能成本,避免在熱路徑 (高頻請求) 大量使用,適合啟動期掃描、開發工具、CLI 命令。
  • PHP 8.0+ 新增 ReflectionClass::getAttributes() 可讀取屬性 (Attributes),替代註解解析。
copyright © 萬盛學電腦網 all rights reserved