萬盛學電腦網

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

PHP 物件導向核心:建構子、解構子與封裝性完整指南

PHP 5 引入了統一的建構子命名慣例(__construct())與全新的解構子機制(__destruct()),配合可視性關鍵字(public、protected、private),奠定了現代 PHP 物件導向程式設計的基礎。本文將系統性說明這三大核心概念的語法、行為與實務應用。

建構子:物件初始化的關鍵

語法與特性

  • 方法名固定為 __construct()(PHP 4 風格的同名建構子仍相容,但不建議使用)
  • 每次 new ClassName() 實例化時自動呼叫,不可手動呼叫
  • 每個類別只能有一個建構子(不支援多載),可透過預設參數或 func_get_args() 實現彈性參數
  • 主要用途:初始化屬性、建立資源連線、註冊事件監聽等

基本範例

class Person {
    public $name;
    public $sex;
    public $age;

    public function __construct($name, $sex, $age) {
        $this->name = $name;
        $this->sex = $sex;
        $this->age = $age;
    }

    public function say() {
        echo "我的名字叫:{$this->name} 性別:{$this->sex} 年齡:{$this->age}
"; } } $p1 = new Person('張三', '男', 20); $p2 = new Person('李四', '女', 30); $p1->say(); // 輸出:我的名字叫:張三 性別:男 年齡:20 $p2->say(); // 輸出:我的名字叫:李四 性別:女 年齡:30

進階技巧:建構子參數預設值與型別宣告(PHP 7.0+)

class Database {
    private $pdo;

    public function __construct(
        string $host = 'localhost',
        string $dbname = 'test',
        string $user = 'root',
        string $pass = '',
        int $port = 3306
    ) {
        $dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4";
        $this->pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]);
    }
}

解構子:資源釋放的最後防線

特性與觸發時機

  • 方法名固定為 __destruct(),不接受任何參數
  • 當物件的所有參考被刪除(unset())或超出作用域、腳本結束時自動呼叫
  • 適用場景:關閉資料庫連線、釋放檔案控制代碼、寫入快取、記錄日誌
  • 注意:腳本終止時(exit()、致命錯誤)解構子仍會執行,但若在解構子中拋出例外會導致致命錯誤

範例:資源自動清理

class FileHandler {
    private $handle;

    public function __construct(string $filename, string $mode = 'r') {
        $this->handle = fopen($filename, $mode);
        if (!$this->handle) {
            throw new RuntimeException("無法開啟檔案:{$filename}");
        }
    }

    public function readAll(): string {
        return fread($this->handle, filesize($filename));
    }

    public function __destruct() {
        if (is_resource($this->handle)) {
            fclose($this->handle);
            echo "檔案控制代碼已釋放
"; } } } $handler = new FileHandler('data.txt'); echo $handler->readAll(); // 腳本結束時自動呼叫 __destruct() 關閉檔案

封裝性:資訊隱藏與存取控制

三種可視性關鍵字

關鍵字類別內部子類別外部程式碼
public✓✓✓
protected✓✓✗
private✓✗✗

封裝性的核心價值

  1. 資料完整性:透過存取器方法驗證輸入,防止非法狀態
  2. 實作細節隱藏:內部邏輯變更不影響外部介面
  3. 降低耦合度:外部依賴介面而非實作
  4. 安全性:敏感資料(密碼、金鑰、個資)不被直接暴露

私有屬性的存取模式

class BankAccount {
    private $balance = 0;
    private $transactionLog = [];

    public function __construct(float $initialBalance = 0) {
        if ($initialBalance < 0) {
            throw new InvalidArgumentException('初始餘額不可為負數');
        }
        $this->balance = $initialBalance;
    }

    // 唯讀存取器
    public function getBalance(): float {
        return $this->balance;
    }

    // 受控寫入器(存款)
    public function deposit(float $amount): bool {
        if ($amount <= 0) return false;
        $this->balance += $amount;
        $this->logTransaction('deposit', $amount);
        return true;
    }

    // 受控寫入器(提款)
    public function withdraw(float $amount): bool {
        if ($amount <= 0 || $amount > $this->balance) return false;
        $this->balance -= $amount;
        $this->logTransaction('withdraw', $amount);
        return true;
    }

    private function logTransaction(string $type, float $amount): void {
        $this->transactionLog[] = [
            'type' => $type,
            'amount' => $amount,
            'balance' => $this->balance,
            'time' => date('Y-m-d H:i:s')
        ];
    }

    public function getTransactionLog(): array {
        return $this->transactionLog; // 回傳副本更安全
    }
}

$account = new BankAccount(1000);
$account->deposit(500);
$account->withdraw(200);
echo "目前餘額:{$account->getBalance()}"; // 1300
// $account->balance = -9999; // 錯誤:Cannot access private property

建構子與封裝性的協作

建構子是初始化私有屬性的主要管道,因為建構子預設為 public,外部可透過建構子參數安全地設定初始狀態:

class User {
    private $id;
    private $email;
    private $passwordHash;
    private $createdAt;

    public function __construct(string $email, string $plainPassword) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('Email 格式錯誤');
        }
        $this->email = $email;
        $this->passwordHash = password_hash($plainPassword, PASSWORD_DEFAULT);
        $this->createdAt = new DateTimeImmutable();
    }

    public function verifyPassword(string $plainPassword): bool {
        return password_verify($plainPassword, $this->passwordHash);
    }

    // 唯讀屬性存取器
    public function getEmail(): string { return $this->email; }
    public function getCreatedAt(): DateTimeImmutable { return $this->createdAt; }
}

常見錯誤與避坑指南

  • 建構子宣告為 private:會導致無法透過 new 實例化(除非使用靜態工廠方法)
  • 解構子中使用其他物件:該物件可能已被銷毀,建議檢查 isset() 或捕獲錯誤
  • 過度使用 public 屬性:違反封裝原則,應改為 private + 存取器
  • 子類別未呼叫父類建構子:若父類有建構子,子類必須显式呼叫 parent::__construct()
  • 在解構子中拋出例外:PHP 會發出 Fatal Error,應改用錯誤記錄

總結

建構子(__construct)負責物件誕生時的初始化,解構子(__destruct)負責物件銷毀前的清理,封裝性(private/protected/public)則定義了物件與外界的互動邊界。三者協同構成了 PHP 物件生命週期管理與資料保護的完整體系。掌握這些核心機制,是編寫健壯、可維護 PHP 程式碼的關鍵。

copyright © 萬盛學電腦網 all rights reserved