萬盛學電腦網

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

PHP 類別完整實戰:建構子、解構子、Clone、__call、序列化與喚醒

前言

PHP 物件導向提供豐富的魔術方法,掌握它們能讓類別設計更靈活、強大。本文透過購物車、Session 管理等實務場景,完整示範 __construct、__destruct、__clone、__call、__sleep、__wakeup 的用法與注意事項。

1. 簡單購物車類別

<?php
class Cart {
    private $items = [];  // 商品陣列 [product_id => quantity]

    // 加入商品
    public function addItem($productId, $qty = 1) {
        if (!isset($this->items[$productId])) {
            $this->items[$productId] = 0;
        }
        $this->items[$productId] += $qty;
    }

    // 移除商品
    public function removeItem($productId, $qty = 1) {
        if (!isset($this->items[$productId])) return false;
        
        if ($this->items[$productId] > $qty) {
            $this->items[$productId] -= $qty;
            return true;
        } else {
            unset($this->items[$productId]);
            return true;
        }
    }

    // 取得所有商品
    public function getItems() {
        return $this->items;
    }

    // 計算總數量
    public function getTotalQty() {
        return array_sum($this->items);
    }
}

// 使用
$cart = new Cart();
$cart->addItem('P001', 2);
$cart->addItem('P002', 1);
print_r($cart->getItems());
?>

2. 建構子與解構子

<?php
class SessionManager {
    public $sessionId;
    public $startTime;

    public function __construct() {
        $this->sessionId = session_id() ?: session_create_id();
        $this->startTime = microtime(true);
        echo "【建構子】Session 啟動: {$this->sessionId}<br>";
    }

    public function __destruct() {
        $duration = round(microtime(true) - $this->startTime, 4);
        echo "【解構子】Session 結束,持續 {$duration} 秒<br>";
        // 可在這裡寫入日誌、釋放資源、關閉資料庫連線
    }
}

$session = new SessionManager();
// 程式結束或 unset($session) 時會自動呼叫 __destruct
?>

3. 物件複製:__clone

預設 clone 是淺層複製,參考型屬性會共享同一物件。需實作 __clone 進行深層複製:

<?php
class Address {
    public $city;
    public function __construct($city) { $this->city = $city; }
}

class User {
    public $name;
    public $address;  // 物件屬性

    public function __construct($name, Address $address) {
        $this->name    = $name;
        $this->address = $address;
    }

    // 深層複製:複製時也複製 address 物件
    public function __clone() {
        $this->address = clone $this->address;
    }
}

$addr = new Address('台北');
$user1 = new User('小明', $addr);
$user2 = clone $user1;  // 觸發 __clone

$user2->name = '小華';
$user2->address->city = '高雄';

echo "User1: {$user1->name}, {$user1->address->city}<br>"; // 小明, 台北
echo "User2: {$user2->name}, {$user2->address->city}<br>"; // 小華, 高雄
?>

4. 方法不存在攔截:__call

呼叫不存在的方法時自動觸發,適合動態代理、API 客戶端:

<?php
class ApiClient {
    private $baseUrl = 'https://api.example.com';

    public function __call($method, $args) {
        // 動態對應 HTTP 方法:getUsers → GET /users
        $httpMethod = substr($method, 0, 3); // get, post, put, del
        $endpoint   = lcfirst(substr($method, 3)); // Users → users
        
        echo "【__call】攔截: {$method}() → {$httpMethod} {$this->baseUrl}/{$endpoint}<br>";
        echo "參數: "; print_r($args);
        
        // 實際會用 cURL 或 Guzzle 發送請求
        return ['status' => 'mock response'];
    }
}

$client = new ApiClient();
$client->getUsers(['page' => 1, 'limit' => 20]);
$client->postOrder(['product_id' => 100, 'qty' => 2]);
?>

5. 序列化與喚醒:__sleep / __wakeup

控制物件序列化時保留哪些屬性,反序列化時重新初始化資源:

<?php
class UserSession {
    public $userId;
    public $permissions = [];
    private $dbConn;      // 資源型態,無法序列化
    private $cacheKey;    // 暫存金鑰,不需序列化

    public function __construct($userId) {
        $this->userId = $userId;
        $this->dbConn = $this->connectDb(); // 建立資料庫連線
        $this->cacheKey = 'user_' . $userId;
    }

    // 序列化前:指定要保留的屬性名稱陣列
    public function __sleep() {
        return ['userId', 'permissions']; // 不包含 dbConn、cacheKey
    }

    // 反序列化後:重新建立資源連線
    public function __wakeup() {
        $this->dbConn = $this->connectDb();
        $this->cacheKey = 'user_' . $this->userId;
        echo "【__wakeup】重新建立資料庫連線<br>";
    }

    private function connectDb() {
        // 實際回傳 PDO 實例
        return "DB_Connection_Resource";
    }
}

// 測試
$session = new UserSession(123);
$session->permissions = ['read', 'write'];

$serialized = serialize($session);
echo "序列化長度: " . strlen($serialized) . "<br>";

$restored = unserialize($serialized);
echo "還原後 userId: {$restored->userId}<br>";
?>

魔術方法速查表

方法觸發時機常見用途
__constructnew 實例化時初始化屬性、建立連線、載入設定
__destruct物件銷毀時(unset、腳本結束)關閉連線、寫入日誌、釋放鎖
__cloneclone 物件時深層複製參考型屬性
__call呼叫不可存取的方法動態方法、API 代理、委派模式
__callStatic靜態呼叫不可存取方法靜態工廠、ActiveRecord 查詢
__sleepserialize() 之前指定序列化屬性、關閉資源
__wakeupunserialize() 之後重新建立資源、初始化暫存
__serialize / __unserializePHP 7.4+ 新介面更精確控制序列化行為

實務建議

  1. 建構子保持單純:複雜初始化改用靜態工廠方法 User::create()
  2. 避免在解構子拋出例外:會導致 Fatal Error,改用 try-catch 內部處理
  3. __clone 必須配合深層複製需求:僅在有參考型屬性時實作
  4. 序列化敏感資料需加密:不要直接序列化含密碼、Token 的物件
  5. 優先使用介面/抽象類別:定義契約,而非依賴具體實作
copyright © 萬盛學電腦網 all rights reserved