類常量用於儲存「類層級、生命週期內不變」的資料。定義使用 const 關鍵字,不需要 也不允許 public/protected/private 修飾符。
class Student {
public int $id;
public string $name;
public string $gender;
// 類常量:慣例全大寫底線分隔
public const GENDER_MALE = '男';
public const GENDER_FEMALE = '女';
public function __construct(int $id, string $name, string $gender = '') {
$this->id = $id;
$this->name = $name;
// self:: 存取當前類常量
$this->gender = $gender ?: self::GENDER_MALE;
}
}
// 存取方式:類名::常量名
echo Student::GENDER_MALE; // 男
echo Student::GENDER_FEMALE; // 女
| 成員類型 | 關鍵字 | 所屬 | 存取方式 |
|---|---|---|---|
| 類常量 | const | 類 | ClassName::CONST |
| 靜態屬性 | static | 類 | ClassName::$prop |
| 非靜態屬性 | (無) | 實例 | $obj->prop |
| 靜態方法 | static function | 類 | ClassName::method() |
| 非靜態方法 | function | 實例 | $obj->method() |
class A {
public function who() {
echo 'A:' . get_class($this) . PHP_EOL;
}
}
class B extends A {
public function test() {
$this->who(); // $this 是 B 實例
}
}
$b = new B();
$b->test(); // 輸出:A:B
// 更極端:靜態呼叫非靜態方法(PHP 7+ 已棄用/嚴格模式報錯)
A::who(); // Deprecated: Non-static method A::who() should not be called statically
// 此時 $this 未定義,若在相容模式下執行,$this 可能來自外層呼叫環境!
結論:$this 代表「當前執行該方法的實例物件」,不取決於方法定義在哪個類,而取決於呼叫時的物件。靜態呼叫非靜態方法會導致 $this 未定義或指向錯誤物件,嚴禁使用。
CLASS_CONSTANT(全大寫 + 底線)static::CONST(晚期靜態綁定)而非 self::CONSTenum 替代大量類常量場景,型別更安全