PHP 物件導向提供豐富的魔術方法,掌握它們能讓類別設計更靈活、強大。本文透過購物車、Session 管理等實務場景,完整示範 __construct、__destruct、__clone、__call、__sleep、__wakeup 的用法與注意事項。
<?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());
?>
<?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
?>
預設 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>"; // 小華, 高雄
?>
呼叫不存在的方法時自動觸發,適合動態代理、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]);
?>
控制物件序列化時保留哪些屬性,反序列化時重新初始化資源:
<?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>";
?>
| 方法 | 觸發時機 | 常見用途 |
|---|---|---|
| __construct | new 實例化時 | 初始化屬性、建立連線、載入設定 |
| __destruct | 物件銷毀時(unset、腳本結束) | 關閉連線、寫入日誌、釋放鎖 |
| __clone | clone 物件時 | 深層複製參考型屬性 |
| __call | 呼叫不可存取的方法 | 動態方法、API 代理、委派模式 |
| __callStatic | 靜態呼叫不可存取方法 | 靜態工廠、ActiveRecord 查詢 |
| __sleep | serialize() 之前 | 指定序列化屬性、關閉資源 |
| __wakeup | unserialize() 之後 | 重新建立資源、初始化暫存 |
| __serialize / __unserialize | PHP 7.4+ 新介面 | 更精確控制序列化行為 |
User::create()