掌握繼承機制、三種存取層級、static 靜態特性、final 限制繼承/覆寫、以及 parent/self/static 關鍵字的正確用法,是 PHP 物件導向程式設計的入門必修課。
class Animal {
private $weight;
public function getWeight() { return $this->weight; }
public function setWeight($w) { $this->weight = $w; }
}
class Dog extends Animal {
public function bark() { echo "Wang~~"; }
}
$dog = new Dog();
$dog->setWeight(20);
echo $dog->getWeight(); // 20
$dog->bark(); // Wang~~
| 修飾詞 | 類別內部 | 子類別 | 外部代碼 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✗ |
| private | ✓ | ✗ | ✗ |
最佳實踐:屬性預設 private,透過 public/protected 方法存取;僅在需子類別直接操作時用 protected。
$this 不可用self::$prop、static::$prop(晚期靜態綁定)parent::$propClassName::$prop、ClassName::method()class Counter {
public static $count = 0;
public function __construct() { self::$count++; }
public static function getCount() { return self::$count; }
}
echo Counter::getCount(); // 0
new Counter(); new Counter();
echo Counter::getCount(); // 2
final class:禁止被繼承final function:禁止被覆寫final class SecurityTool { /* ... */ }
// class Hack extends SecurityTool {} // Fatal error
class Base {
final public function critical() { /* 不可覆寫 */ }
}
| 關鍵字 | 用途 | 存取靜態屬性 | 存取靜態方法 | 存取類別常數 | 存取實例屬性 | 存取實例方法 |
|---|---|---|---|---|---|---|
| self | 當前類別(編譯期綁定) | ✓ | ✓ | ✓ | ✗ | ✓ |
| static | 實際調用類別(運行期綁定,LSB) | ✓ | ✓ | ✓ | ✗ | ✓ |
| parent | 父類別 | ✓ | ✓ | ✓ | ✗ | ✓ |
| $this-> | 當前實例 | ✗ | ✗ | ✗ | ✓ | ✓ |
class A {
public static function who() { echo __CLASS__; }
public static function testSelf() { self::who(); }
public static function testStatic() { static::who(); }
}
class B extends A {
public static function who() { echo __CLASS__; }
}
B::testSelf(); // A(self 綁定寫死在 A)
B::testStatic(); // B(static 依實際調用類別)
熟練掌握存取控制、static 語義、final 限制、以及 self/static/parent 的綁定時機,能寫出封裝良好、擴展性強的 PHP 類別體系。