魔術方法是 PHP 物件導程式設計的核心機制,以雙底線 __ 開頭,在特定情境自動被呼叫。掌握它們能寫出更優雅、擴充性更強的程式碼。
| 方法 | 觸發時機 | PHP 版本 |
|---|---|---|
| __construct() | 物件建立時 | 5.0+ |
| __destruct() | 物件銷毀前 | 5.0+ |
| __call() | 呼叫不可存取的實例方法 | 5.0+ |
| __callStatic() | 呼叫不可存取的靜態方法 | 5.3+ |
| __get() | 讀取不可存取的屬性 | 5.0+ |
| __set() | 寫入不可存取的屬性 | 5.0+ |
| __isset() | 對不可存取屬性呼叫 isset() | 5.0+ |
| __unset() | 對不可存取屬性呼叫 unset() | 5.0+ |
| __sleep() | serialize() 前 | 5.0+ |
| __wakeup() | unserialize() 後 | 5.0+ |
| __toString() | 物件當字串使用時 | 5.0+ |
| __invoke() | 物件當函式呼叫時 | 5.3+ |
| __set_state() | var_export() 導出類別時 | 5.1+ |
| __clone() | clone 物件時 | 5.0+ |
| __serialize() | serialize() 時 (新介面) | 7.4+ |
| __unserialize() | unserialize() 時 (新介面) | 7.4+ |
<?php
class Database {
private $conn;
public function __construct($config) {
echo "建立連線...\n";
$this->conn = new mysqli($config['host'], $config['user'], $config['pass'], $config['db']);
}
public function __destruct() {
if ($this->conn) {
echo "關閉連線...\n";
$this->conn->close();
}
}
}
$db = new Database(['host'=>'localhost', 'user'=>'root', 'pass'=>'', 'db'=>'test']);
// 程式結束或 unset($db) 時自動呼叫 __destruct
?>
<?php
class Entity {
private $data = [];
private $allowed = ['name', 'email', 'age'];
public function __get($name) {
if (in_array($name, $this->allowed)) {
return $this->data[$name] ?? null;
}
throw new Exception("屬性 '$name' 不存在或不可讀");
}
public function __set($name, $value) {
if (in_array($name, $this->allowed)) {
$this->data[$name] = $value;
return;
}
throw new Exception("屬性 '$name' 不存在或不可寫");
}
public function __isset($name) {
return in_array($name, $this->allowed) && isset($this->data[$name]);
}
public function __unset($name) {
if (in_array($name, $this->allowed)) {
unset($this->data[$name]);
}
}
}
$user = new Entity();
$user->name = "張三"; // __set
echo $user->name; // __get -> 張三
echo isset($user->email); // __isset -> false
unset($user->name); // __unset
?>
<?php
class Router {
public function __call($method, $args) {
echo "動態方法: $method(" . implode(', ', $args) . ")\n";
// 可實作動態路由、代理模式等
}
public static function __callStatic($method, $args) {
echo "靜態動態方法: $method(" . implode(', ', $args) . ")\n";
}
}
$router = new Router();
$router->get('/users', 'UserController@index'); // __call
Router::post('/login', 'AuthController@login'); // __callStatic
<?php
class UserSession {
public $user_id;
public $name;
private $db_connection; // 資源不可序列化
private $cache; // 快取不需序列化
public function __sleep() {
// 只回傳需序列化的屬性名稱
return ['user_id', 'name'];
}
public function __wakeup() {
// 反序列化後重建資源
$this->db_connection = new mysqli('localhost', 'root', '', 'db');
$this->cache = new Redis();
}
}
$session = new UserSession();
$session->user_id = 1;
$session->name = 'Admin';
$serialized = serialize($session);
// 只包含 user_id, name
$restored = unserialize($serialized);
// 自動呼叫 __wakeup 重建連線
?>
<?php
class Money {
private $amount;
private $currency;
public function __construct(float $amount, string $currency = 'TWD') {
$this->amount = $amount;
$this->currency = $currency;
}
public function __toString(): string {
return "{$this->currency} " . number_format($this->amount, 2);
}
}
$price = new Money(1234.5);
echo $price; // TWD 1,234.50
echo "價格: $price"; // 自動呼叫 __toString
// printf("%s", $price); // 也支援
<?php
class Multiplier {
private $factor;
public function __construct($factor) {
$this->factor = $factor;
}
public function __invoke($value) {
return $value * $this->factor;
}
}
$double = new Multiplier(2);
$triple = new Multiplier(3);
echo $double(5); // 10
echo $triple(5); // 15
// 可作為 callable 傳遞
$numbers = [1, 2, 3];
echo array_sum(array_map(new Multiplier(10), $numbers)); // 60
<?php
class Order {
public $id;
public $items = [];
public $created_at;
public function __clone() {
// 深層複製 items 陣列
$this->items = array_map(fn($item) => clone $item, $this->items);
$this->created_at = new DateTime(); // 重設時間
$this->id = 0; // 新訂單需重新分配 ID
}
}
$order1 = new Order();
$order1->id = 1001;
$order1->items = [new OrderItem('商品A'), new OrderItem('商品B')];
$order2 = clone $order1;
// $order2->items 為新陣列,元素為新物件,不影響 $order1
?>
<?php
class Settings {
public $debug = false;
public $theme = 'dark';
// var_export() 導出時
public static function __set_state(array $props) {
$obj = new self();
foreach ($props as $k => $v) $obj->$k = $v;
return $obj;
}
// PHP 7.4+ 新序列化介面 (效能更好、支援型別)
public function __serialize(): array {
return ['debug' => $this->debug, 'theme' => $this->theme];
}
public function __unserialize(array $data): void {
$this->debug = $data['debug'];
$this->theme = $data['theme'];
}
}
$settings = new Settings();
$export = var_export($settings, true);
// 產生可執行的 PHP 程式碼重建物件
eval('$restored = ' . $export . ';');
__toString、__destruct 中拋出例外會導致 Fatal Error__ 開頭命名自訂方法