萬盛學電腦網

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

PHP 靜態延遲綁定 示例與原理解析

概念解析

靜態延遲綁定 解決繼承體系中「靜態方法/屬性引用當前類而非父類」的問題。關鍵字 static:: (PHP 5.3+) 在**運行時**解析為實際調用的類,而非定義時的類。

核心示例

<?php
class A {
    protected static $def = '123456';

    public static function test(): void
    {
        // 晚期靜態綁定:返回實際調用的類名
        echo get_class(new static()) . "\n"; // 等同於 static::class (PHP 8.0+)
    }

    public static function test2(): void
    {
        // 訪問靜態屬性:繼承類可覆蓋
        echo static::$def . "\n";
    }
}

class B extends A {
    protected static $def = '456789';
}

class C extends A {
    protected static $def = 'abcdef';
}

// 測試
echo "=== test() 獲取實際類名 ===\n";
B::test(); // 輸出: B
C::test(); // 輸出: C
A::test(); // 輸出: A

echo "\n=== test2() 訪問靜態屬性 ===\n";
B::test2(); // 輸出: 456789 (B 的覆蓋值)
C::test2(); // 輸出: abcdef (C 的覆蓋值)
A::test2(); // 輸出: 123456 (A 的原始值)

對比:self:: vs static::

<?php
class ParentClass {
    public static $value = 'parent';
    
    public static function showSelf(): void {
        echo "self::\$value = " . self::$value . "\n"; // 編譯期綁定 -> ParentClass
    }
    
    public static function showStatic(): void {
        echo "static::\$value = " . static::$value . "\n"; // 運行期綁定 -> 實際調用類
    }
}

class ChildClass extends ParentClass {
    public static $value = 'child';
}

ParentClass::showSelf();  // parent
ParentClass::showStatic(); // parent
ChildClass::showSelf();   // parent (self 綁定到定義處)
ChildClass::showStatic(); // child  (static 綁定到調用處)

實際應用場景

1. Active Record 基類自動表名

<?php
abstract class Model {
    protected static string $table = '';
    
    public static function table(): string
    {
        // 子類未顯式聲明 $table 時,自動推斷為類名小寫複數
        return static::$table ?: strtolower((new ReflectionClass(static::class))->getShortName()) . 's';
    }
    
    public static function find(int $id): ?static
    {
        $db = Database::connection();
        $sql = "SELECT * FROM " . static::table() . " WHERE id = ?";
        $row = $db->fetch($sql, [$id]);
        return $row ? new static($row) : null;
    }
}

class User extends Model {
    // 自動推斷表名為 'users',或顯式聲明 protected static $table = 'custom_users';
}

class Order extends Model {
    protected static string $table = 'orders';
}

$user = User::find(1);    // 查詢 users 表
$order = Order::find(1);  // 查詢 orders 表

2. 工廠方法模式

<?php
abstract class PaymentGateway {
    abstract public function charge(float $amount): bool;
    
    public static function create(string $type): static
    {
        return match ($type) {
            'alipay' => new AlipayGateway(),
            'wechat' => new WechatGateway(),
            'stripe' => new StripeGateway(),
            default => throw new InvalidArgumentException("Unknown gateway: $type"),
        };
    }
}

class AlipayGateway extends PaymentGateway { /* ... */ }
class WechatGateway extends PaymentGateway { /* ... */ }

// 使用:返回類型為實際子類型 (PHP 8.0+ static 返回類型)
$gateway = PaymentGateway::create('alipay'); // AlipayGateway 實例

3. 單例模式正確實作

<?php
abstract class Singleton {
    private static array $instances = [];
    
    protected function __construct() {}
    public function __clone() { throw new Exception('Cannot clone singleton'); }
    public function __wakeup() { throw new Exception('Cannot unserialize singleton'); }
    
    public static function getInstance(): static
    {
        $class = static::class; // 晚期綁定獲取子類類名
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new static();
        }
        return self::$instances[$class];
    }
}

class Config extends Singleton { /* ... */ }
class Logger extends Singleton { /* ... */ }

$config = Config::getInstance(); // Config 實例
$logger = Logger::getInstance(); // Logger 實例,互不干擾

注意事項與陷阱

  • static:: **不能**用於非靜態上下文 (如實例方法中用 static::$prop 會報錯),實例方法用 self::$prop 或 $this->prop (非靜態屬性)。
  • forward_static_call() / forward_static_call_array() 可動態調用靜態方法並保持晚期綁定。
  • 性能:static:: 比 self:: 微慢 (需運行時解析),但可忽略不計。
  • PHP 8.0+ 可用 static::class 直接獲取類名字串,替代 get_class(new static())。

靜態延遲綁定是 PHP 實現「可擴展的靜態架構」關鍵機制,配合 static 返回類型 (PHP 8.0) 構建優雅的繼承體系。

copyright © 萬盛學電腦網 all rights reserved