static 是 PHP 面向對象編程中最核心、最易誤解的關鍵字之一。它涉及**靜態屬性/方法**、**靜態變量**、**晚期靜態綁定 (LSB)**、靜態調用非靜態的陷阱等多個維度。本文通過圖解內存模型、代碼實驗、最佳實踐,徹底釐清 static 的所有行為。
+------------------+ +------------------+
| Class Foo | | Instance $obj |
|------------------| |------------------|
| static $count = 0| | $instanceProp |
| static function | | |
| bar() { ... } | | |
+------------------+ +------------------+
▲ ▲
│ │
└────── 共享同一份 ─────────┘
<?php
class Counter {
public static int $count = 0;
public int $instanceCount = 0;
public static function increment(): void {
self::$count++; // 類內部訪問靜態:self::
// $this->count++; // ❌ 錯誤:靜態方法中無 $this
}
public function instanceIncrement(): void {
$this->instanceCount++;
self::$count++; // 實例方法可訪問靜態
}
}
// 外部訪問
Counter::$count; // ✅ 推薦:類名::
Counter::increment(); // ✅
$obj = new Counter();
$obj->instanceIncrement(); // ✅
$obj::$count; // ✅ 物件也可訪問靜態 (但不推薦,語義混淆)
$obj->increment(); // ❌ 致命錯誤:非靜態調用靜態方法 (PHP 8.0+ 拋出 Error)
?>
static 在函數內部聲明的變量,**僅初始化一次**,生命週期贯穿整個腳本執行,但作用域僅限該函數內部。
<?php
function generator() {
static $id = 0; // 只初始化一次
return ++$id;
}
echo generator(); // 1
echo generator(); // 2
echo generator(); // 3
// 遞歸計數器
function depth($n) {
static $maxDepth = 0;
if ($n > $maxDepth) $maxDepth = $n;
if ($n <= 0) return $maxDepth;
return depth($n - 1);
}
echo depth(5); // 5
// ❌ 初始化只能用常量/常量表達式
function foo() {
static $a = 1 + 2; // ✅ 常量表達式
static $b = strlen('a'); // ❌ PHP 8.0+ 允許,舊版報錯
static $c = new A(); // ❌ 物件不可作為靜態初始值
}
?>
這是 **最核心、最易錯** 的知識點。
<?php
class ParentClass {
public static string $name = 'Parent';
public static function whoAmI(): void {
echo "self: " . self::$name . "\n"; // 永遠指向 ParentClass::$name
}
public static function whoAmILate(): void {
echo "static: " . static::$name . "\n"; // 運行時綁定到調用類
}
}
class ChildClass extends ParentClass {
public static string $name = 'Child';
}
ParentClass::whoAmI(); // self: Parent
ChildClass::whoAmI(); // self: Parent ← 關鍵!self 綁定到定義它的類
ParentClass::whoAmILate(); // static: Parent
ChildClass::whoAmILate(); // static: Child ← 晚期靜態綁定生效
?>
<?php
abstract class Model {
protected static string $table = '';
// 靜態工廠方法:創建當前子類實例
public static function create(array $attributes): static { // PHP 8.0+ 返回類型 static
$instance = new static(); // LSB: 實例化調用的具體子類
foreach ($attributes as $k => $v) {
$instance->$k = $v;
}
return $instance;
}
public static function find(int $id): ?static {
// 查詢邏輯...
return new static(); // 返回子類實例
}
// 獲取表名:子類必須覆寫或遵循約定
public static function getTable(): string {
return static::$table ?: strtolower((new ReflectionClass(static::class))->getShortName());
}
}
class User extends Model {
protected static string $table = 'users';
}
$user = User::create(['name' => 'John']); // 返回 User 實例
echo get_class($user); // 'User'
?>
<?php
class Demo {
public string $name = 'instance';
public static string $staticName = 'static';
public function instanceMethod() {
echo "Instance: $this->name\n"; // 正常
echo "Static: " . self::$staticName . "\n"; // 正常
}
public static function staticMethod() {
echo "Static: " . self::$staticName . "\n"; // 正常
// echo $this->name; // ❌ Fatal Error: Using $this when not in object context
}
}
// PHP 7: E_DEPRECATED "Non-static method should not be called statically"
// PHP 8+: Error "Non-static method Demo::instanceMethod() cannot be called statically"
Demo::instanceMethod(); // ❌ 絕對禁止
Demo::staticMethod(); // ✅
$obj = new Demo();
$obj->instanceMethod(); // ✅
$obj->staticMethod(); // ✅ 但語義混淆,不推薦
?>
<?php
trait CounterTrait {
public static int $count = 0; // 每個使用該 Trait 的類擁有獨立副本
public static function increment(): void {
self::$count++; // 綁定到使用該 Trait 的具體類
}
}
class A { use CounterTrait; }
class B { use CounterTrait; }
A::increment(); // A::$count = 1
B::increment(); // B::$count = 1 (獨立)
echo A::$count . ' ' . B::$count; // 1 1
?>
| 修飾符 | 類內 | 子類 | 外部 | 繼承行為 |
|---|---|---|---|---|
public static | ✅ | ✅ | ✅ Class::$prop | 子類可覆寫,父子各自一份存儲 |
protected static | ✅ | ✅ | ❌ | 子類可覆寫/訪問父類 parent::$prop |
private static | ✅ | ❌ | ❌ | 子類不可見,定義同名屬性互不干擾 |
static getInstance() 是全局狀態偽裝,難以 Mock、難以並行測試。改用容器管理單例生命週期。static::**,包括:工廠方法、ActiveRecord 查詢、配置獲取、事件分發。const 或 public static readonly (PHP 8.1+)。public static readonly string $API_URL = '...'; 初始化後不可修改,編譯期常量化。<?php
class HeavyService {
public static ?self $instance = null; // 單例持有
private array $hugeCache = [];
public static function getInstance(): self {
return self::$instance ??= new self();
}
}
// 問題:$hugeCache 永不釋放,佔用內存直到進程結束
// 解決:定期清理、弱引用、或避免靜態持有大對象
?>
| 場景 | 關鍵字 | 綁定時機 | 典型用例 |
|---|---|---|---|
| 類內訪問自身靜態 | self:: | 編譯期 | 內部常量、工具方法調用 |
| 類內訪問調用類靜態 | static:: | 運行期 (LSB) | 工廠方法、獲取表名、ActiveRecord |
| 子類訪問父類靜態 | parent:: | 編譯期 | 調用父類構造、父類方法 |
| 外部訪問靜態 | ClassName:: | 編譯期 | 配置讀取、單例獲取、工具方法 |
| 函數內保持狀態 | static $var | 首次執行初始化 | 計數器、緩存、遞歸深度 |