PHP `static` 關鍵字在不同語境下行為截然不同:函數內靜態區域變數、類別靜態屬性、全域靜態變數。本文深度解析三者記憶體模型、生命週期、作用域與實戰應用場景。
<?php
function counter() {
static $count = 0; // 只執行一次
$count++;
echo "呼叫次數: $count\n";
}
counter(); // 呼叫次數: 1
counter(); // 呼叫次數: 2
counter(); // 呼叫次數: 3
// 錯誤示範:初始值不能是運算式
// static $sum = 1 + 1; // PHP 7: Parse error, PHP 8.1+: 允許常數運算式
// 存取失敗:作用域限制
// echo $count; // Notice: Undefined variable
<?php
// 遞迴深度計數
function recursiveDepth($n) {
static $depth = 0;
$depth++;
if ($n <= 0) {
$max = $depth;
$depth = 0; // 重置供下次呼叫
return $max;
}
return recursiveDepth($n - 1);
}
// 函數級快取(簡易 Memoization)
function fibonacci(int $n): int {
static $cache = [];
if ($n <= 1) return $n;
if (isset($cache[$n])) return $cache[$n];
return $cache[$n] = fibonacci($n - 1) + fibonacci($n - 2);
}
// 類別單例輔助(非執行緒安全)
function getDatabaseConnection(): PDO {
static $instance = null;
if ($instance === null) {
$instance = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
}
return $instance;
}
<?php
class Config {
private static string $env = 'production';
private static array $settings = [];
public static function setEnv(string $env): void {
self::$env = $env;
}
public static function get(string $key, $default = null): mixed {
return self::$settings[$key] ?? $default;
}
public static function load(array $config): void {
self::$settings = $config;
}
}
// 晚期靜態綁定 (LSB) 示範
class Model {
protected static string $table = 'base_table';
public static function getTable(): string {
return static::$table; // 解析為實際呼叫的子類別
}
}
class User extends Model {
protected static string $table = 'users';
}
class Post extends Model {
protected static string $table = 'posts';
}
echo User::getTable(); // users
echo Post::getTable(); // posts
<?php
// file: utils/string_helpers.php
// 檔案層級靜態變數:僅此檔案可見
static int $callCount = 0;
static array $cache = [];
function slugify(string $str): string {
global $callCount; // 若需修改檔案靜態變數,需 global(但不推薦)
// 更好:使用函數內 static
static $callCount = 0;
$callCount++;
// ... slugify 邏輯
return strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $str), '-'));
}
// 另一個檔案無法存取 $callCount,避免命名衝突
| 特性 | 函數內 static | 類別 static | 檔案層級 static |
|---|---|---|---|
| 宣告位置 | 函數內部 | 類別內部 | 函數/類別外部 |
| 作用域 | 函數內部 | 類別作用域(可 public/protected/private) | 檔案內部 |
| 存取方式 | 直接變數名 | `self::$prop`、`Class::$prop` | 直接變數名(需 global 修改) |
| 共享範圍 | 同一函數所有呼叫 | 所有實例、靜態呼叫 | 同一檔案所有函數/代碼 |
| 繼承行為 | 不適用 | 支援繼承與 LSB | 不適用 |
| 典型用途 | 計數器、快取、單例輔助、遞迴狀態 | 設定、共用資源、工廠、單例 | 模組私有狀態、避免全域污染 |
請求開始
│
├─► 編譯階段:分配靜態變數記憶體(函數 static、類別 static、檔案 static)
│
├─► 第一次呼叫函數:執行 static 初始化賦值
│
├─► 後續呼叫:讀取/修改現有記憶體位置
│
├─► 類別實例化:共享靜態屬性記憶體
│
└─► 請求結束:所有靜態變數記憶體釋放
(PHP 是請求級生命週期,無持久化跨請求能力)
<?php
// 錯誤認知:static 變數在下一次 HTTP 請求仍保留值
// 事實:PHP 是無狀態、請求隔離,每請求重新初始化所有 static
// 跨請求持久化需用:Session、資料庫、Redis、檔案、APCu
<?php
// 危險:多請求共享修改靜態屬性(雖 PHP 通常單執行緒,但 OPcache/JIT 可能有競態)
class DangerousCounter {
public static int $count = 0;
public function increment() { self::$count++; }
}
// 安全:唯讀配置、不可變物件、或使用原子操作(Redis/資料庫)