萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 類別繼承與擴展完整指南:從基礎語法到設計模式應用

繼承核心機制

PHP 採用單繼承模型:一個子類別只能繼承一個父類別,但可實作多個介面。繼承建立「是一種」關係,子類別自動獲得父類別的 public、protected 成員,private 成員不可直接存取。

基礎語法與關鍵字

<?php
// 父類別 (基礎類別)
class Thread
{
    // 屬性可見性
    public string $topic;      // 公開:任意存取
    protected string $body;    // 受保護:本類 + 子類
    private string $author;    // 私有:僅本類
    private DateTimeImmutable $date;
    
    // 建構子
    public function __construct(string $topic, string $body, string $author)
    {
        $this->topic = $topic;
        $this->body = $body;
        $this->author = $author;
        $this->date = new DateTimeImmutable();
    }
    
    // 公開方法
    public function send(): bool
    {
        return $this->validate() && $this->insertToDb();
    }
    
    public function edit(string $newBody): bool
    {
        $this->body = $newBody;
        return $this->updateDb();
    }
    
    public function delete(): bool
    {
        return $this->checkPermission() && $this->deleteFromDb();
    }
    
    // 受保護方法:子類可覆寫/呼叫
    protected function validate(): bool
    {
        return strlen($this->topic) > 0 && strlen($this->body) > 0;
    }
    
    // 私有方法:子類不可見
    private function insertToDb(): bool { /* ... */ return true; }
    private function updateDb(): bool { /* ... */ return true; }
    private function checkPermission(): bool { /* ... */ return true; }
    private function deleteFromDb(): bool { /* ... */ return true; }
}

// 子類別繼承
class MainThread extends Thread
{
    public int $id;
    public string $board;
    public bool $allowReply = true;
    
    // 子類建構子:通常呼叫 parent::__construct()
    public function __construct(int $id, string $board, string $topic, string $body, string $author)
    {
        $this->id = $id;
        $this->board = $board;
        parent::__construct($topic, $body, $author); // 必須呼叫父建構子
    }
    
    // 方法覆寫
    public function send(): bool
    {
        // 子類邏輯
        if (!$this->allowReply) return false;
        
        // 呼叫父類方法
        return parent::send(); 
    }
    
    public function edit(string $newBody): bool
    {
        // 子類擴充邏輯
        $this->logEdit($newBody);
        return parent::edit($newBody);
    }
    
    // 子類專有方法
    public function pin(): void { /* ... */ }
    public function lock(): void { /* ... */ }
    
    private function logEdit(string $newBody): void
    {
        error_log("Thread {$this->id} edited: " . substr($newBody, 0, 50));
    }
}

// instanceof 類型檢查
$thread = new MainThread(1, 'php', '標題', '內容', '作者');
var_dump($thread instanceof Thread);    // true
var_dump($thread instanceof MainThread); // true
?>

關鍵字詳細說明

關鍵字用途注意事項
extends類別繼承單繼承,不可多重
parent::呼叫父類方法/屬性靜態綁定,非晚期靜態綁定
final禁止繼承/覆寫final class、final function
abstract抽象類別/方法不可實例化,強制子類實作
static::晚期靜態綁定 (LSB)解決 self:: 靜態綁定問題

晚期靜態綁定 (LSB) 實戰

<?php
class Model
{
    protected static string $table = 'base_table';
    
    public static function getTable(): string
    {
        // self::$table 永遠是 'base_table'
        // static::$table 會解析為實際調用的子類
        return static::$table;
    }
    
    public static function create(array $data): static
    {
        // PHP 8.0+ 回傳型別 static 表示當前類別
        $instance = new static(); // 實例化調用的子類
        // 填充資料...
        return $instance;
    }
}

class User extends Model
{
    protected static string $table = 'users';
}

class Post extends Model
{
    protected static string $table = 'posts';
}

echo User::getTable();  // users
echo Post::getTable();  // posts

$user = User::create(['name' => 'John']); // 回傳 User 實例
$post = Post::create(['title' => 'Hi']);  // 回傳 Post 實例
?>

設計模式應用:模板方法模式

<?php
abstract class DataExporter
{
    // 模板方法:定義算法骨架
    final public function export(string $destination): bool
    {
        $data = $this->fetchData();
        $formatted = $this->format($data);
        return $this->write($destination, $formatted);
    }
    
    // 子類必須實作
    abstract protected function fetchData(): array;
    abstract protected function format(array $data): string;
    abstract protected function write(string $dest, string $content): bool;
    
    // 可選覆寫的鉤子方法
    protected function beforeExport(): void {}
    protected function afterExport(bool $success): void {}
}

class CsvExporter extends DataExporter
{
    protected function fetchData(): array
    {
        return User::all()->toArray();
    }
    
    protected function format(array $data): string
    {
        $fp = fopen('php://memory', 'w');
        fputcsv($fp, array_keys($data[0] ?? []));
        foreach ($data as $row) fputcsv($fp, $row);
        rewind($fp);
        return stream_get_contents($fp);
    }
    
    protected function write(string $dest, string $content): bool
    {
        return file_put_contents($dest, $content) !== false;
    }
}

class JsonExporter extends DataExporter
{
    protected function fetchData(): array { return Post::all()->toArray(); }
    protected function format(array $data): string { return json_encode($data, JSON_PRETTY_PRINT); }
    protected function write(string $dest, string $content): bool { return file_put_contents($dest, $content) !== false; }
}

// 使用
$csv = new CsvExporter();
$csv->export('storage/exports/users.csv');

$json = new JsonExporter();
$json->export('storage/exports/posts.json');
?>

組合優於繼承:策略模式替代方案

<?php
// ❌ 繼承導致類別爆炸
class Bird { public function fly(): void {} }
class Eagle extends Bird {}
class Penguin extends Bird { public function fly(): void { throw new Exception('企鵝不會飛'); } }

// ✅ 組合:行為介面 + 策略注入
interface FlyBehavior
{
    public function fly(): void;
}

class FlyWithWings implements FlyBehavior
{
    public function fly(): void { echo "飛行中...\n"; }
}

class CannotFly implements FlyBehavior
{
    public function fly(): void { echo "無法飛行\n"; }
}

class Bird
{
    public function __construct(
        private FlyBehavior $flyBehavior
    ) {}
    
    public function performFly(): void
    {
        $this->flyBehavior->fly();
    }
    
    public function setFlyBehavior(FlyBehavior $fb): void
    {
        $this->flyBehavior = $fb;
    }
}

// 運行時動態切換行為
$eagle = new Bird(new FlyWithWings());
$penguin = new Bird(new CannotFly());

$eagle->performFly();   // 飛行中...
$penguin->performFly(); // 無法飛行

// 甚至可動態變更
$penguin->setFlyBehavior(new FlyWithWings());
$penguin->performFly(); // 飛行中... (裝上噴射背包)
?>

常見繼承陷阱與避坑

  1. 建構子未呼叫 parent:導致父類初始化邏輯缺失
  2. 過度繼承層級:超過 3 層難以維護,改用組合
  3. 破壞里氏替換原則 (LSP):子類行為違背父類契約 (如企鵝飛行拋異常)
  4. 私有方法無法覆寫:需改為 protected 或提取為介面
  5. self:: vs static:::靜態方法繼承時必須用 static:: 實現多型

總結

PHP 繼承提供代碼復用與多型基礎,但組合優於繼承是現代設計原則。善用:abstract 定義契約、final 防止濫用繼承、static:: 實現 LSB、Trait 復用橫切關注點、策略模式替代深層繼承。記住:繼承代表「是一種」,組合代表「擁有某能力」。

copyright © 萬盛學電腦網 all rights reserved