static關鍵字定義的屬性與方法屬於**類**而非實例,所有實例共享同一份內存。本文從內存模型出發,系統講解調用規則、繼承行為、晚靜態綁定交互及常見誤區。
$this。$this指向調用對象。| 調用者 \ 目標 | 靜態屬性 | 非靜態屬性 | 靜態方法 | 非靜態方法 |
|---|---|---|---|---|
| 類名:: | ✅ Class::$prop | ❌ 無$this | ✅ Class::method() | ⚠️ 可調用但<$this>未定義(PHP 8.1+ 棄用) |
| 對象-> | ✅ $obj::$prop(推薦Class::$prop) | ✅ $obj->prop | ✅ $obj::method() | ✅ $obj->method() |
| 類內部 self:: | ✅ self::$prop | ❌ | ✅ self::method()(編譯期綁定) | ✅ self::method()(轉為靜態調用,無$this) |
| 類內部 static:: | ✅ static::$prop(運行期綁定) | ❌ | ✅ static::method()(晚綁定) | ✅ static::method()(晚綁定,轉為靜態調用) |
| 類內部 $this-> | ✅ $this->prop(僅讀,寫入創建實例屬性遮蔽) | ✅ | ✅ $this->method()(實例調用) | ✅ |
<?php
class Human {
public static $name = '小妹';
public $height = 180;
public static function tell() {
echo self::$name . "\n"; // 靜態方法調用靜態屬性
// echo $this->height; // Fatal: Using $this when not in object context
}
public function say() {
echo self::$name . " 說話了\n"; // 普通方法用self調用靜態屬性
echo $this->height . "\n";
}
}
$p = new Human();
$p->say();
$p->tell(); // 對象調用靜態方法:合法
echo $p::$name; // 對象訪問靜態屬性:合法
// Human::say(); // Deprecated: Non-static method called statically
static::配合覆寫實現多態(見延遲靜態綁定文章)。const MAX = 100不可變、編譯期解析、無內存開銷。getInstance()返回。$this:PHP 8.1+拋出棄用警告。清晰理解靜態成員內存語義,能避免難以排查的共享狀態Bug,編寫更健壯的面向對象代碼。