用於類別內部存取 static 屬性或 const 常數:
class A {
private static $name = "static A";
const PI = 3.14;
public $value = "non-static";
public static function getName() {
return self::$name; // 正確
}
public static function getValue() {
return self::$value; // 錯誤:靜態方法不可存取非靜態屬性
}
public function getPI() {
return self::PI; // 正確
}
}
口訣:static 方法只能用 self:: 存取 static / const 成員。
用於物件內部存取非靜態屬性與方法:
class A {
public $value = "instance";
public function setValue($v) {
$this->value = $v; // 正確
}
}
const PI = 3.14;(不加 $)。self::PI 或 A::PI。const ARR = [1,2,3];)。static $var:函數內靜態區域變數,跨呼叫保持值。static::$prop / static::method():PHP 5.3+ 延遲靜態繫結(LSB),解決繼承時 self:: 綁定父類的問題。存取物件實例的屬性與方法:$obj->prop、$obj->method()。
| 語法 | 適用對象 | 範例 |
|---|---|---|
self::$x | static 屬性 / const 常數 | 類別內部 |
$this->x | 實例屬性 / 方法 | 物件內部 |
Class::$x | static 屬性 / const | 類別外部 |
$obj->x | 實例屬性 / 方法 | 物件外部 |
static::$x | LSB 晚期靜態繫結 | 繼承體系中 |
牢記:「靜態用 self/Class,實例用 $this/物件」,即可避開 90% 錯誤。