萬盛學電腦網

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

PHP 靜態屬性與靜態方法深度解析:static 關鍵字、記憶體共享、調用規則與進階模式

核心概念

  • static 關鍵字:修飾屬性/方法,歸屬於類別本身,而非某個實例
  • 類屬性/類方法:不需實例化即可透過 類別名::成員 存取
  • 記憶體特性:靜態屬性在記憶體中僅存在一份,所有實例共享

靜態屬性

定義與存取

<?php
class User {
    private static $count = 0;  // 靜態屬性
    
    public function __construct() {
        self::$count++;         // 內部存取:self::
    }
    
    public function getCount() {
        return self::$count;
    }
    
    public function __destruct() {
        self::$count--;
    }
}

$user1 = new User();
$user2 = new User();
$user3 = new User();
echo "Current users: " . $user1->getCount() . "\n"; // 3

unset($user3);
echo "Current users: " . $user1->getCount() . "\n"; // 2
?>

外部直接存取(無需實例化)

<?php
class Math {
    public static $pi = 3.14;
}

$r = 3;
echo "Area: " . Math::$pi * $r * $r . "\n";  // 28.26

// 運行時動態修改(影響所有後續存取)
Math::$pi = 3.141592653589793;
echo "Precise Area: " . Math::$pi * $r * $r . "\n"; // 28.2743338823
?>

靜態屬性初始化限制

  • 只能初始化為字面值或常數:static $x = 1;、static $x = 'str';、static $x = SOME_CONST;
  • 不可使用運算式:static $x = 1+1;、static $x = func();、static $x = new Class(); → Parse Error
  • PHP 8.1+ 可搭配 readonly:public static readonly string $version = '1.0';

靜態方法

定義與調用

<?php
class Math {
    public static function max($a, $b) {
        return $a > $b ? $a : $b;
    }
    
    public static function max3($a, $b, $c) {
        // 內部調用同類靜態方法:推薦 self::
        $max = self::max($a, $b);
        $max = self::max($max, $c);
        return $max;
    }
}

echo Math::max(99, 88);   // 99
echo Math::max3(99, 77, 88); // 99
?>

調用靜態屬性

<?php
class Circle {
    public static $pi = 3.14;
    
    public static function area($r) {
        // 推薦 self:: 而非 類別名::
        return $r * $r * self::$pi;
    }
}

echo Circle::area(3); // 28.26
?>

關鍵限制:靜態語境無法存取非靜態成員

❌ 錯誤:靜態方法存取非靜態屬性

<?php
class Circle {
    public $pi = 3.14;  // 非靜態
    
    public static function area($r) {
        return $r * $r * self::$pi;  // Fatal Error: Undefined class constant 'pi'
    }
}
?>

❌ 錯誤:靜態方法使用 $this

<?php
class Circle {
    public $pi = 3.14;
    
    public static function area($r) {
        return $r * $r * $this->pi;  // Fatal Error: Using $this when not in object context
    }
}
?>

⚠️ 陷阱:非靜態方法被 static:: 調用會被視為靜態

<?php
class Math {
    public $pi = 3.14;
    
    public function max($a, $b) {  // 非靜態
        echo self::$pi;  // 這裡 self::$pi 會報錯,因為 $pi 非靜態
        return $a > $b ? $a : $b;
    }
    
    public static function max3($a, $b, $c) {
        // 以 static:: 呼叫非靜態方法 → PHP 視為靜態調用
        $m = self::max($a, $b);  // 此時 max() 在靜態語境執行
        return self::max($m, $c);
    }
}

Math::max3(1,2,3); // Fatal Error: Access to undeclared static property: Math::$pi
?>

規則:以 self::/類別名::/static:: 呼叫非靜態方法時,該方法在靜態語境執行,內部不可使用 $this、不可存取非靜態屬性。

Late Static Binding(靜態延遲綁定):static:: vs self::

<?php
class Base {
    public static function who() {
        echo __CLASS__ . "\n";
    }
    
    public static function test() {
        self::who();    // 編譯期綁定 → Base
        static::who();  // 運行期綁定 → 實際調用類別
    }
}

class Derived extends Base {
    public static function who() {
        echo __CLASS__ . "\n";
    }
}

Derived::test();
// 輸出:
// Base   (self::)
// Derived (static::)
?>

實用模式:單例模式

<?php
class Database {
    private static $instance = null;
    private $pdo;
    
    private function __construct() {
        $this->pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
    }
    
    // 禁止克隆
    private function __clone() {}
    // 禁止反序列化
    public function __wakeup() {
        throw new Exception("Cannot unserialize singleton");
    }
    
    public static function getInstance(): self {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function getPdo(): PDO {
        return $this->pdo;
    }
}

// 使用
$pdo = Database::getInstance()->getPdo();
?>

實用模式:靜態工廠方法

<?php
class User {
    private $id, $name, $email;
    
    private function __construct($id, $name, $email) {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }
    
    public static function create(string $name, string $email): self {
        // 驗證、生成 ID、資料庫寫入...
        $id = random_int(10000, 99999);
        return new self($id, $name, $email);
    }
    
    public static function fromArray(array $data): self {
        return new self($data['id'], $data['name'], $data['email']);
    }
}

$user = User::create('Alice', 'alice@example.com');
?>

總結

場景關鍵字存取方式注意事項
共享計數器/配置/快取static 屬性self::$prop / Class::$prop僅字面值初始化,記憶體單份共享
工具方法/無狀態邏輯static 方法self::method() / Class::method()不可用 $this、不可存取非靜態成員
繼承體系中多型調用static::static::method()Late Static Binding,運行期解析實際類別
單例/工廠/註冊表static 方法 + 私有建構子Class::getInstance()控制實例化邏輯,全域唯一存取點

善用 static 能實現無狀態服務、全域共享狀態、受控實例化,但濫用會導致強耦合、難以測試、全域狀態汙染。原則:優先實例方法,需共享狀態或無狀態工具時再考慮 static,並配合依賴注入容器管理生命週期。

copyright © 萬盛學電腦網 all rights reserved