萬盛學電腦網

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

PHP 物件型別檢測:instanceof、get_class、Reflection 完整指南

型別檢測方法對比

方法用途支援繼承支援介面效能
instanceof檢查物件是否為類別/介面實例✅✅極快 (opcode 優化)
is_a()函數版 instanceof✅✅稍慢 (函數呼叫)
get_class()取得確切類別名稱❌ 只回傳實際類別❌快
get_parent_class()取得父類別名稱✅❌快
class_implements()取得實作的介面清單❌✅中等
ReflectionClass完整型別內省✅✅較慢 (建構開銷)

instanceof 核心用法

<?php
interface Loggable {}
interface Serializable {}

class BaseModel implements Loggable {}
class User extends BaseModel implements Serializable {}
class Post extends BaseModel {}

$user = new User();
$post = new Post();

// 基本檢查
var_dump($user instanceof User);      // true
var_dump($user instanceof BaseModel); // true (繼承)
var_dump($user instanceof Loggable);  // true (介面)
var_dump($user instanceof Serializable); // true
var_dump($post instanceof Serializable); // false

// 否定檢查
if (!($user instanceof Post)) {
    echo "不是 Post 物件\n";
}

// 字串類別名 (PHP 8.0+)
$className = 'User';
var_dump($user instanceof $className); // true

// null 安全
$nullObj = null;
var_dump($nullObj instanceof User); // false (不拋出錯誤)
?>

ReflectionClass 完整型別內省

<?php
class Service
{
    public function __construct(
        private readonly string $name,
        private readonly array $tags = []
    ) {}
    
    public function process(): void {}
    protected function internal(): void {}
    private function secret(): void {}
}

$reflection = new ReflectionClass(Service::class);

// 類別基本資訊
echo "名稱: " . $reflection->getName() . "\n";
echo "命名空間: " . $reflection->getNamespaceName() . "\n";
echo "檔案: " . $reflection->getFileName() . "\n";
echo "起始行: " . $reflection->getStartLine() . "\n";
echo "結束行: " . $reflection->getEndLine() . "\n";
echo "是抽象: " . ($reflection->isAbstract() ? '是' : '否') . "\n";
echo "是最終: " . ($reflection->isFinal() ? '是' : '否') . "\n";
echo "是介面: " . ($reflection->isInterface() ? '是' : '否') . "\n";
echo "是 Trait: " . ($reflection->isTrait() ? '是' : '否') . "\n";

// 繼承關係
echo "父類別: " . ($reflection->getParentClass()?->getName() ?? '無') . "\n";
echo "實作介面: " . implode(', ', $reflection->getInterfaceNames()) . "\n";
echo "使用 Trait: " . implode(', ', array_keys($reflection->getTraits())) . "\n";

// 常數
foreach ($reflection->getConstants() as $name => $value) {
    echo "常數: $name = $value\n";
}

// 屬性 (含私有)
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE) as $prop) {
    $prop->setAccessible(true);
    echo "屬性: {$prop->getName()} = " . var_export($prop->getDefaultValue(), true) . "\n";
}

// 方法
foreach ($reflection->getMethods() as $method) {
    echo "方法: {$method->getName()}()";
    echo " 公開: " . ($method->isPublic() ? '是' : '否');
    echo " 靜態: " . ($method->isStatic() ? '是' : '否');
    echo " 抽象: " . ($method->isAbstract() ? '是' : '否');
    echo "\n";
}

// 實例化 (無需呼叫建構子)
$instance = $reflection->newInstanceWithoutConstructor();
// 或帶參數實例化
$instance = $reflection->newInstanceArgs(['MyService', ['api', 'vip']]);

// 讀取私有屬性
$prop = $reflection->getProperty('name');
$prop->setAccessible(true);
echo $prop->getValue($instance); // MyService

// 呼叫私有方法
$method = $reflection->getMethod('secret');
$method->setAccessible(true);
$method->invoke($instance);
?>

實戰場景:動態服務解析器

<?php
interface ServiceInterface {}

class Container
{
    private array $bindings = [];
    
    public function bind(string $abstract, callable $concrete): void
    {
        $this->bindings[$abstract] = $concrete;
    }
    
    public function make(string $abstract): mixed
    {
        if (!isset($this->bindings[$abstract])) {
            // 自動解析:檢查類別是否存在且可實例化
            if (class_exists($abstract)) {
                return $this->resolve($abstract);
            }
            throw new Exception("未綁定: $abstract");
        }
        
        return $this->bindings[$abstract]($this);
    }
    
    private function resolve(string $class): object
    {
        $reflection = new ReflectionClass($class);
        
        if (!$reflection->isInstantiable()) {
            throw new Exception("無法實例化: $class");
        }
        
        $constructor = $reflection->getConstructor();
        if (!$constructor) {
            return $reflection->newInstance();
        }
        
        $dependencies = [];
        foreach ($constructor->getParameters() as $param) {
            $type = $param->getType();
            if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
                $depClass = $type->getName();
                $dependencies[] = $this->make($depClass); // 遞歸解析依賴
            } elseif ($param->isDefaultValueAvailable()) {
                $dependencies[] = $param->getDefaultValue();
            } else {
                throw new Exception("無法解析參數: {$param->getName()}");
            }
        }
        
        return $reflection->newInstanceArgs($dependencies);
    }
}

// 使用
$container = new Container();
$container->bind(ServiceInterface::class, fn($c) => new Service('custom', ['tag1']));

$service = $container->make(ServiceInterface::class); // 自動解析依賴
$service = $container->make('Service'); // 直接類別名也可
?>

型別檢測最佳實踐

1. 型別收窄

<?php
function process(mixed $input): string
{
    if ($input instanceof \DateTimeInterface) {
        return $input->format('Y-m-d');
    }
    
    if (is_array($input)) {
        return json_encode($input);
    }
    
    if (is_string($input)) {
        return strtoupper($input);
    }
    
    return (string) $input;
}
?>

2. 避免過度檢測:使用多型

<?php
// ❌ 違反開閉原則:每新增類型需修改此函數
function calculatePrice(Product $product): float
{
    if ($product instanceof Book) return $product->price * 0.9;
    if ($product instanceof Electronic) return $product->price * 1.1;
    if ($product instanceof Clothing) return $product->price;
    return $product->price;
}

// ✅ 正確:多型分發
interface Pricable
{
    public function calculatePrice(): float;
}

class Book implements Pricable
{
    public function __construct(public float $price) {}
    public function calculatePrice(): float { return $this->price * 0.9; }
}

class Electronic implements Pricable
{
    public function __construct(public float $price) {}
    public function calculatePrice(): float { return $this->price * 1.1; }
}

function calculatePrice(Pricable $product): float
{
    return $product->calculatePrice(); // 多型分發
}
?>

3. 型別斷言輔助函數

<?php
/** @template T */
/** @param class-string $class */
/** @param mixed $value */
/** @return T */
function assertInstanceOf(string $class, mixed $value): mixed
{
    if (!$value instanceof $class) {
        throw new TypeError("Expected $class, got " . (is_object($value) ? get_class($value) : gettype($value)));
    }
    return $value;
}

// 使用:IDE 可識別回傳型別
$user = assertInstanceOf(User::class, $container->make(User::class));
$user->sendEmail(); // IDE 自動完成
?>

效能考量

  • instanceof 編譯為單一 opcode (INSTANCEOF),極快,熱路徑可放心使用
  • ReflectionClass 建構有開銷,建議快取:static $reflections = []; $reflections[$class] ??= new ReflectionClass($class);
  • 大量物件型別檢測時,考慮加入 type 欄位或使用 get_class() 字串比較

總結

instanceof 是日常型別檢測首選,支援繼承與介面;get_class() 用於取得確切類別名 (日誌、序列化);ReflectionClass 用於框架級開發 (DI 容器、序列化器、ORM、測試工具)。核心原則:能用多型解決就不用型別檢測,型別檢測是邊界處理工具,而非核心業務邏輯。

copyright © 萬盛學電腦網 all rights reserved