<?php
function counter() {
static $count = 0; // 僅初始化一次
$count++;
echo $count . PHP_EOL;
}
counter(); // 1
counter(); // 2
counter(); // 3
?>
PHP 要求靜態變量初始值為編譯時常量,以下寫法均會導致解析錯誤:
<?php
function test() {
static $a = 0 + 1; // 錯誤:表達式
static $b = sqrt(121); // 錯誤:函數調用
static $c = SOME_CONST; // 正確:常量
static $d = 'string'; // 正確:字面量
}
?>
解決方案:在函數體內首次調用時判斷並賦值:
<?php
function test() {
static $a;
if ($a === null) { // 首次調用
$a = sqrt(121); // 此處可用任意表達式
}
// ...
}
?>
function fibonacci($n) {
static $cache = [0 => 0, 1 => 1];
if (isset($cache[$n])) return $cache[$n];
return $cache[$n] = fibonacci($n - 1) + fibonacci($n - 2);
}
function getConfig($key) {
static $config = null;
if ($config === null) {
$config = parse_ini_file(__DIR__ . '/config.ini', true);
}
return $config[$key] ?? null;
}
function nextId($prefix = '') {
static $id = 0;
return $prefix . ++$id;
}
| 特性 | 函數內 static 變量 | 類 static 屬性 |
|---|---|---|
| 訪問方式 | $var | self::$var / Class::$var |
| 繼承行為 | 無關 | 父子類共享同一存儲(Late Static Binding 除外) |
| 可見性 | 僅函數內 | public/protected/private |
static 變量是 PHP 實現「有狀態函數」的關鍵工具,適用於計數器、緩存、單例資源等場景。牢記初始化只能用常量,複雜邏輯移至運行時判斷賦值即可繞過限制。