萬盛學電腦網

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

PHP 類別/函數/方法存在性檢查與反射大全:function_exists、class_exists、is_callable 與魔術常數

PHP 提供豐富的執行期反射能力,讓你能動態檢查類別、函數、方法是否存在、取得名稱、參數、屬性等中繼資料。本文系統整理 7 大核心檢查函數、3 大魔術常數、反射 API 實戰用法,並說明動態呼叫的效能與安全考量。

核心存在性檢查函數對比

函數用途回傳值自動載入觸發適用對象
function_exists()檢查函數是否已定義bool否函數 (含內建、使用者定義)
class_exists()檢查類別/介面/特徵是否已定義bool是 (預設 $autoload=true)類別、介面、Trait
interface_exists()檢查介面是否已定義bool是介面
trait_exists()檢查 Trait 是否已定義bool是Trait
method_exists()檢查類別/物件是否有指定方法bool是 (若類別未載入)物件實例、類別名稱
property_exists()檢查類別/物件是否有指定屬性bool是物件實例、類別名稱
is_callable()檢查變數是否為合法可呼叫結構bool否 (不觸發自動載入)函數名、靜態方法、物件方法、閉包、invokable 物件

關鍵差異:class_exists vs is_callable

<?php
class Foo {
    public function bar() {}
    public static function baz() {}
}

$obj = new Foo();

// class_exists: 檢查類別定義存在 (觸發 autoload)
var_dump(class_exists('Foo'));           // true
var_dump(class_exists('NonExist'));      // false

// method_exists: 檢查方法存在 (需類別已載入)
var_dump(method_exists($obj, 'bar'));    // true
var_dump(method_exists('Foo', 'baz'));   // true (靜態方法)
var_dump(method_exists('Foo', 'none'));  // false

// is_callable: 檢查「可被呼叫」 (不觸發 autoload,更安全)
var_dump(is_callable('Foo::baz'));       // true (靜態方法字串)
var_dump(is_callable([$obj, 'bar']));    // true (物件方法)
var_dump(is_callable('non_exist_func')); // false (不觸發 autoload)
var_dump(is_callable('NonExist::method'));// false (不觸發 autoload)

// 關鍵差異:is_callable 不會觸發自動載入,適合「檢查後才決定是否載入」場景
if (is_callable('HeavyClass::heavyMethod')) {
    // 這裡才 require 或 autoload
}

魔術常數:編譯期解析、效能最佳

常數含義範例輸出注意事項
__FUNCTION__當前函數名稱 (區分大小寫)myFunction全域函數/方法內有效;PHP 4 為小寫
__METHOD__當前類別方法名稱 (含類別名)MyClass::myMethodPHP 5.0+;靜態/非靜態皆適用
__CLASS__當前類別名稱 (含命名空間)App\Models\UserPHP 4.3+;Trait 中表使用該 Trait 的類別
__TRAIT__當前 Trait 名稱App\Traits\LoggablePHP 5.4+
__NAMESPACE__當前命名空間App\ControllersPHP 5.3+
__FILE__當前檔案完整路徑 (已解析符號連結)/var/www/app/Http/Controllers/UserController.php包含檔中表被包含檔路徑
__DIR__當前檔案目錄 (等同 dirname(__FILE__))/var/www/app/Http/ControllersPHP 5.3+
__LINE__當前行號42除錯、日誌常用

實戰範例:動態載入與 Plugin 系統

<?php
// Plugin 介面
interface PluginInterface {
    public function getName(): string;
    public function execute(array $params): mixed;
}

// 動態載入器
class PluginLoader {
    private string $pluginDir;
    private array $loaded = [];
    
    public function __construct(string $pluginDir) {
        $this->pluginDir = $pluginDir;
    }
    
    public function load(string $name): ?PluginInterface {
        if (isset($this->loaded[$name])) return $this->loaded[$name];
        
        $file = $this->pluginDir . '/' . $name . '/' . $name . '.php';
        if (!is_file($file)) return null;
        
        // 安全檢查:檔案內是否定義了符合介面的類別
        $code = file_get_contents($file);
        if (!preg_match('/class\s+(\w+)\s+implements\s+PluginInterface/', $code)) {
            throw new RuntimeException("Plugin $name 不符合介面規範");
        }
        
        require_once $file;
        
        // 掃描檔案中定義的類別
        $classes = get_declared_classes();
        $newClasses = array_diff($classes, get_declared_classes()); // 邏輯需調整,這裡示意
        
        // 實際做法:約定類別名 = PluginName + 'Plugin'
        $className = ucfirst($name) . 'Plugin';
        if (!class_exists($className)) {
            throw new RuntimeException("找不到類別 $className");
        }
        
        if (!is_subclass_of($className, PluginInterface::class)) {
            throw new RuntimeException("$className 未實作 PluginInterface");
        }
        
        $instance = new $className();
        $this->loaded[$name] = $instance;
        return $instance;
    }
    
    public function call(string $plugin, string $method, array $args = []): mixed {
        $instance = $this->load($plugin);
        if (!$instance) throw new RuntimeException("Plugin $plugin 不存在");
        
        if (!method_exists($instance, $method)) {
            throw new BadMethodCallException("Method $method 不存在");
        }
        
        return $instance->$method(...$args);
    }
}

// 使用
$loader = new PluginLoader(__DIR__ . '/plugins');
$result = $loader->call('image', 'resize', ['width' => 800, 'height' => 600]);

Reflection API 進階應用 (PHP 8+ 屬性支援)

<?php
#[Attribute(Attribute::TARGET_METHOD)]
class Route {
    public function __construct(
        public string $method,
        public string $path,
        public array $middleware = []
    ) {}
}

class UserController {
    #[Route('GET', '/users')]
    public function index() { /* ... */ }
    
    #[Route('POST', '/users', ['auth', 'validate'])]
    public function store() { /* ... */ }
}

// 掃描路由屬性
$refClass = new ReflectionClass(UserController::class);
foreach ($refClass->getMethods() as $refMethod) {
    $attrs = $refMethod->getAttributes(Route::class);
    foreach ($attrs as $attr) {
        $route = $attr->newInstance();
        echo "{$route->method} {$route->path} -> {$refMethod->name}()\n";
        // 輸出: GET /users -> index()
        //       POST /users -> store()
    }
}

// 參數型別提示檢查 (用於自動注入)
$params = $refMethod->getParameters();
foreach ($params as $param) {
    $type = $param->getType();
    if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
        $className = $type->getName(); // 取得型別類別名
        // 從容器解析...
    }
}

效能考量與最佳實踐

  1. 避免重複檢查:將檢查結果快取 (靜態變數/APCu)。
  2. 優先用 is_callable:不觸發 autoload,適合條件式載入。
  3. 生產環境關閉自動載入檢查:Composer classmap_authoritative 或 optimize-autoloader 將類別對應編譯成陣列,class_exists 變極快。
  4. 反射較慢:熱路徑避免大量反射;啟動時掃描建立快取 (如路由表、DI 容器定義)。
  5. 安全性:動態呼叫 $obj->$method() 或 $class::$method() 前,務必白名單驗證方法名,防 RCE。

常見陷阱

method_exists 回傳 true 但呼叫失敗
方法可能是 private/protected、需特定參數、或被 __call 魔術方法處理。用 ReflectionMethod::isPublic() 進一步檢查。
class_exists('Parent') 在子類別中為 true
正常行為,class_exists 檢查類別定義存在,繼承鏈不影響。
命名空間陷阱
class_exists('User') 在命名空間 App 中會找 App\User;跨命名空間需用完整名稱 \App\Models\User 或 User::class。
function_exists 不支援命名空間函數
需用完整名稱 function_exists('App\Helpers\helper_func')。

掌握 PHP 反射與存在性檢查,能構建靈活的插件系統、自動路由、依賴注入容器、序列化器等核心基礎設施。記住:編譯期魔術常數最快、is_callable 最安全、Reflection 最強大但最慢,根據場景選擇正確工具!

copyright © 萬盛學電腦網 all rights reserved