PHP OOP 從入門到精通:封裝、繼承、多態與現代最佳實踐
面向對象程式設計是構建可維護、可擴展 PHP 應用的基石。本文系統講解類與對象、可見性、繼承、多態、魔術方法、介面、Trait、靜態綁定等核心機制,並對比舊版寫法與現代語法。
一、類與對象基礎
1. 類定義與實例化(現代語法 PHP 8+)
<?php
declare(strict_types=1);
namespace App\Models;
class User {
// 屬性類型聲明(PHP 7.4+)
public string $name;
protected int $age;
private string $email;
// 唯讀屬性(PHP 8.1+)
public readonly string $id;
public readonly \DateTimeImmutable $createdAt;
// 構造函數屬性提升(PHP 8.0+)
public function __construct(
string $id,
string $name,
int $age,
string $email
) {
$this->id = $id;
$this->name = $name;
$this->age = $age;
$this->email = $email;
$this->createdAt = new \DateTimeImmutable();
}
// 方法
public function greet(): string {
return "你好,我是 {$this->name}";
}
}
// 實例化
$user = new User(
id: 'usr_123',
name: '張三',
age: 25,
email: 'zhang@example.com'
);
echo $user->greet(); // 你好,我是張三
echo $user->id; // usr_123(唯讀,不可修改)
// $user->id = 'new'; // Error: Cannot modify readonly property
?>
2. 可見性對比
| 關鍵字 | 類內部 | 子類 | 外部 | 用途 |
| public | ✓ | ✓ | ✓ | 公共 API |
| protected | ✓ | ✓ | ✗ | 內部實現、子類擴展 |
| private | ✓ | ✗ | ✗ | 核心邏輯封裝 |
最佳實踐:屬性默認 private,通過 getter/setter 控制訪問;僅在明確需要子類覆寫時用 protected。
二、封裝與魔術方法
1. 訪問器模式
<?php
class Product {
private float $price = 0.0;
private int $stock = 0;
// 僅讀取器
public function getPrice(): float {
return $this->price;
}
// 寫入器含驗證
public function setPrice(float $price): void {
if ($price < 0) {
throw new \InvalidArgumentException('價格不能為負數');
}
$this->price = $price;
}
public function getStock(): int {
return $this->stock;
}
public function decreaseStock(int $qty): bool {
if ($qty <= 0 || $qty > $this->stock) return false;
$this->stock -= $qty;
return true;
}
}
// PHP 8.2+ readonly + 建構子屬性提升可減少樣板代碼
// 但業務邏輯驗證仍需顯式方法
?>
2. 魔術方法:__get、__set、__isset、__unset
<?php
class DynamicProperties {
private array $data = [];
// 讀取不可見/不存在屬性
public function __get(string $name): mixed {
return $this->data[$name] ?? null;
}
// 寫入不可見/不存在屬性
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
// isset() / empty() 檢查
public function __isset(string $name): bool {
return isset($this->data[$name]);
}
// unset() 操作
public function __unset(string $name): void {
unset($this->data[$name]);
}
// 調試用:獲取所有動態屬性
public function getAll(): array {
return $this->data;
}
}
$obj = new DynamicProperties();
$obj->dynamicProp = 'value'; // 觸發 __set
echo $obj->dynamicProp; // 觸發 __get
var_dump(isset($obj->dynamicProp)); // 觸發 __isset
unset($obj->dynamicProp); // 觸發 __unset
?>
3. 其他重要魔術方法
| 方法 | 觸發時機 | 典型用途 |
| __construct() | 實例化時 | 初始化、依賴注入 |
| __destruct() | 對象銷毀時 | 資源清理、關閉連接 |
| __call() | 調用不可見方法 | 代理、動態方法 |
| __callStatic() | 調用不可見靜態方法 | 靜態代理 |
| __toString() | 對象作字符串使用 | 日志、輸出友好表示 |
| __invoke() | 對象作函數調用 | 可調用對象、策略模式 |
| __sleep() | serialize() 前 | 指定序列化屬性 |
| __wakeup() | unserialize() 後 | 重建資源連接 |
| __serialize() | 序列化(PHP 7.4+) | 自定義序列化數據 |
| __unserialize() | 反序列化(PHP 7.4+) | 自定義反序列化邏輯 |
| __clone() | clone 關鍵字 | 深拷貝、重置標識符 |
| __debugInfo() | var_dump() 時 | 控制調試輸出 |
三、繼承與多態
1. 基礎繼承
<?php
abstract class Animal {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
// 抽象方法:強制子類實現
abstract public function makeSound(): string;
// 普通方法:可被覆寫
public function introduce(): string {
return "我是 {$this->name}";
}
// final 方法:禁止覆寫
final public function getSpecies(): string {
return static::class;
}
}
class Dog extends Animal {
public function makeSound(): string {
return '汪汪!';
}
// 覆寫父類方法
public function introduce(): string {
return parent::introduce() . ",是一隻狗";
}
}
class Cat extends Animal {
public function makeSound(): string {
return '喵~';
}
}
$dog = new Dog('旺財');
echo $dog->introduce(); // 我是旺財,是一隻狗
echo $dog->makeSound(); // 汪汪!
?>
2. 多態實戰:策略模式
<?php
// 支付策略介面
interface PaymentStrategy {
public function pay(float $amount): bool;
public function getName(): string;
}
// 具體策略
class AlipayStrategy implements PaymentStrategy {
public function pay(float $amount): bool {
// 支付寶支付邏輯
return true;
}
public function getName(): string { return '支付寶'; }
}
class WechatStrategy implements PaymentStrategy {
public function pay(float $amount): bool {
// 微信支付邏輯
return true;
}
public function getName(): string { return '微信支付'; }
}
// 上下文
class PaymentContext {
public function __construct(private PaymentStrategy $strategy) {}
public function setStrategy(PaymentStrategy $strategy): void {
$this->strategy = $strategy;
}
public function executePayment(float $amount): bool {
echo "使用 {$this->strategy->getName()} 支付 ¥{$amount}\n";
return $this->strategy->pay($amount);
}
}
// 使用
$context = new PaymentContext(new AlipayStrategy());
$context->executePayment(99.00);
$context->setStrategy(new WechatStrategy());
$context->executePayment(199.00);
?>
四、介面 vs 抽象類 vs Trait
| 特性 | 介面 | 抽象類 | Trait |
| 多重實現 | implements 多個 | 單繼承 | use 多個 |
| 狀態(屬性) | 不可有(常量除外) | 可有 | 可有 |
| 構造函數 | 無 | 可有 | 無(但可用 __construct) |
| 方法實現 | PHP 8.0+ 可有默認實現 | 可有 | 必須有實現 |
| 用途 | 定義契約、類型約束 | 共享代碼+強制規範 | 橫向代碼復用 |
Trait 衝突解決
<?php
trait Loggable {
public function log(string $msg): void {
echo "[LOG] $msg\n";
}
}
trait Debuggable {
public function log(string $msg): void {
echo "[DEBUG] $msg\n";
}
}
class Service {
use Loggable, Debuggable {
// 解決衝突:重命名、調整可見性
Loggable::log as public logInfo;
Debuggable::log as public logDebug;
// 或指定優先
// Loggable::log insteadof Debuggable;
}
public function doWork(): void {
$this->logInfo('工作開始');
$this->logDebug('調試信息');
}
}
?>
五、靜態綁定:self vs static
<?php
class ParentClass {
public static function who(): string {
return 'Parent';
}
public static function testSelf(): string {
return self::who(); // 編譯時綁定:ParentClass
}
public static function testStatic(): string {
return static::who(); // 運行時綁定:調用類
}
}
class ChildClass extends ParentClass {
public static function who(): string {
return 'Child';
}
}
echo ParentClass::testSelf(); // Parent
echo ParentClass::testStatic(); // Parent
echo ChildClass::testSelf(); // Parent(self 綁定父類)
echo ChildClass::testStatic(); // Child(static 晚期靜態綁定)
?>
六、現代 PHP OOP 最佳實踐清單
- 嚴格類型:
declare(strict_types=1) + 完整類型聲明
- 不可變性:優先
readonly 屬性、DateTimeImmutable、值對象
- 組合優於繼承:使用介面 + Trait + 委託替代深層繼承
- 依賴倒置:依賴抽象(介面)而非具體實現
- 單一職責:一個類只做一件事
- 避免 getter/setter 濫用:行為豐富的領域模型 > 貧血模型
- 不可變值對象:Money、Email、Address 等作為值對象
- 工廠方法/構建器:複雜對象創建封裝
- 最終類:
final class 防止意外繼承,除非設計為可擴展
- 靜態分析:PHPStan/Psalm 最高級別檢查
七、經典設計模式在 PHP 中的實現
- 工廠模式:
UserFactory::createFromArray()
- 建造者模式:
QueryBuilder->select()->where()->get()
- 單例模式:DI 容器管理(見單例模式專文)
- 觀察者模式:事件分發器
EventDispatcher
- 策略模式:支付、導出、驗證策略
- 裝飾器模式:中間件、緩存裝飾器
- 適配器模式:第三方 API 統一介面