| 方式 | 語法 | 需實例化 | 訪問靜態 | 訪問非靜態 |
|---|---|---|---|---|
| 對象調用 | $obj->method() | 是 | ✓ (不推薦) | ✓ |
| 類名調用 | Class::method() | 否 | ✓ | ⚠ 有條件 |
| 內部調用 | self:: / parent:: / $this-> | 視上下文 | self:: | $this-> |
<?php
class A {
public $name = 'A';
public function show() {
// 允許:無 $this、無調用非靜態成員
echo "static call ok\n";
}
public function show2() {
// 禁止:使用了 $this
echo $this->name; // 類名調用時報錯:Non-static method...
}
}
A::show(); // 成功
A::show2(); // 錯誤:Non-static method A::show2() cannot be called statically
<?php
class ParentClass {
public static $country = '中國';
public static function say() { echo self::$country . "\n"; }
}
class ChildClass extends ParentClass {
public static $country = 'USA'; // 重新聲明,屬於子類
public function test() {
echo self::$country; // USA (當前類)
echo parent::$country; // 中國 (父類)
}
}
echo ParentClass::$country; // 中國
echo ChildClass::$country; // USA
ChildClass::say(); // 中國 (self:: 綁定定義時類)
?>
| 關鍵字 | 綁定時機 | 用途 |
|---|---|---|
self:: | 編譯期 (定義該類時) | 訪問當前類靜態成員 |
parent:: | 編譯期 | 訪問父類靜態成員 |
static:: | 運行期 (調用該類時) | 晚期靜態綁定,多態場景 |
class A { public static function who() { echo "A\n"; } public static function test() { self::who(); static::who(); } }
class B extends A { public static function who() { echo "B\n"; } }
B::test();
// 輸出:
// A (self:: 綁定 A)
// B (static:: 解析為實際調用類 B)
<?php
function counter() {
static $count = 0; // 僅初始化一次,生命周期 = 腳本運行期
$count++;
echo "Call $count\n";
}
counter(); // Call 1
counter(); // Call 2
counter(); // Call 3
<?php
function test() {
static $a = 0; // ✓ 常量
static $b = 1 + 2; // ✗ 表達式 (PHP 5.6+ 支持常量表達式)
static $c = strlen('abc'); // ✗ 函數調用
static $d = [1,2,3]; // ✗ 數組 (PHP 5.6+ 支持)
}
PHP 5.6+ 允許常量表達式,但不允許函數調用、變量引用。
<?php
function countToTen() {
static $count = 0;
$count++;
echo $count . "\n";
if ($count < 10) countToTen();
$count--; // 回溯還原 (演示作用域生命周期)
}
countToTen();
// 輸出 1 2 3 4 5 6 7 8 9 10
static public $config = [...]static $cache = [] 避免全局變量污染PHP static 關鍵字定義「類級別」成員與「函數級持久化」變量。核心記憶點:
self:: 編譯期綁定,static:: 運行期綁定 (LSB)$this 依賴的非靜態方法 (不推薦)static $var 實現閉包狀態保持