| 維度 | 普通變量 | static 靜態變量 |
|---|---|---|
| 內存區域 | 棧區(函數調用銷毀) | 靜態存儲區(進程生命週期) |
| 初始化 | 每次調用重新初始化 | **僅首次調用初始化一次** |
| 值保持 | 函數結束銷毀 | 跨調用保持值 |
| 作用域 | 局部(函數內) | 局部(函數內)但生命週期全局 |
| 全局 static | 外部可見(extern) | 僅當前文件可見(內部鏈接) |
// 普通變量:每次調用重置
function counterNormal() {
$count = 0;
echo $count++;
}
counterNormal(); // 0
counterNormal(); // 0
// 靜態變量:跨調用累加
function counterStatic() {
static $count = 0;
echo $count++;
}
counterStatic(); // 0
counterStatic(); // 1
counterStatic(); // 2
function recursiveCounter() {
static $count = 0;
$count++;
echo $count . "\n";
if ($count < 5) recursiveCounter();
$count--; // 回溯還原
}
recursiveCounter();
// 輸出:1 2 3 4 5
靜態變量為遞歸提供共享計數器,無需全局變量污染命名空間。
class User {
public static $instanceCount = 0;
public function __construct() { self::$instanceCount++; }
public static function getCount() { return self::$instanceCount; }
}
new User(); new User(); new User();
echo User::getCount(); // 3
$this,不可訪問非靜態成員self:: 綁定父類,static:: (LSB) 綁定調用類class Base {
public static function factory() { return new self(); }
public static function factoryLSB() { return new static(); }
}
class Child extends Base {}
Base::factory(); // Base 實例
Child::factory(); // Base 實例(self 綁定寫死)
Child::factoryLSB(); // Child 實例(static 晚期綁定)
// file_a.php
static $secret = 'internal'; // 僅 file_a 可見
$public = 'shared'; // 外部可見
// file_b.php
include 'file_a.php';
echo $public; // shared
// echo $secret; // 錯誤:未定義
作用:避免全局命名衝突,實現文件級私有狀態。
// ❌ 錯誤:靜態變量只能用字面量/常量初始化
static $x = 1 + 2;
static $y = strlen("abc");
static $z = SOME_CONST; // ✅ 常量允許
// ✅ 正確
static $a = 1;
static $b = 'hello';
static $c = [1,2,3]; // PHP 5.6+ 允許陣列
staticstatic 屬性new static() 配合 LSBconst 或 define(),語義更清晰