<?php
// People.php
class People {
protected $_age;
protected $_name;
protected $_gender;
public function __construct($age, $name, $gender) {
$this->_age = $age;
$this->_name = $name;
$this->_gender = $gender;
}
public function getName() {
return $this->_name;
}
public function hi() {
return $this->_name . ' say hi';
}
}
<?php
// Man.php
require_once 'People.php';
class Man extends People {
public function __construct($age, $name) {
// 呼叫父類別建構子,固定性別為 '男'
parent::__construct($age, $name, '男');
}
// 方法覆寫:改寫 hi() 行為
public function hi() {
// 選項一:完全取代
echo 'Man ' . $this->getName() . ' say hi';
// 選項二:擴充父類別行為(取消註解)
// echo parent::hi() . ' (from Man)';
}
}
<?php // index.php require_once 'Man.php'; $m = new Man(10, 'Vito'); echo $m->hi(); // 輸出: Man Vito say hi
| 概念 | 關鍵字 | 說明 |
|---|---|---|
| 繼承 | extends | 子類別取得父類別 public/protected 成員 |
| 建構子鏈 | parent::__construct() | 子類別需主動呼叫父建構子完成初始化 |
| 方法覆寫 | 同名方法定義 | 子類別方法取代父類別,可選擇呼叫 parent::method() |
| 可見性 | protected | 允許子類別存取,禁止外部存取 |
| 多型 | 型別提示 People $p | 傳入 Man 實例亦符合 People 型別要求 |
class People {
// 禁止子類別覆寫
final public function getSpecies() {
return 'Human';
}
}
class Man extends People {
// 錯誤:Cannot override final method
// public function getSpecies() { return 'Male Human'; }
}
interface Greetable {
public function greet();
}
abstract class People implements Greetable {
// 強制子類別實作
abstract public function work();
public function greet() {
return "Hello, I'm {$this->_name}";
}
}
class Man extends People {
public function work() {
return 'Working hard...';
}
}
掌握繼承鏈、建構子責任鏈、覆寫策略與 final/abstract 約束,是 PHP 物件導向設計的核心基石。