萬盛學電腦網

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

PHP 魔術方法完整指南:__construct 到 __serialize 的 13 個方法詳解

魔術方法是 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+

核心方法詳細說明

1. __construct / __destruct:生命週期

<?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
?>

2. __get / __set / __isset / __unset:屬性多載

<?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
?>

3. __call / __callStatic:方法多載

<?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

4. __sleep / __wakeup:序列化控制

<?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 重建連線
?>

5. __toString:物件轉字串

<?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);  // 也支援

6. __invoke:可呼叫物件

<?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

7. __clone:深層複製控制

<?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
?>

8. __set_state / __serialize / __unserialize

<?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
  • 必須為 public:所有魔術方法必須宣告為 public
  • __callStatic 必須 static:PHP 強制要求
  • 命名保留:除非要用魔術功能,否則不要以 __ 開頭命名自訂方法
  • 效能考量:魔術方法有額外開銷,高頻呼叫路徑避免濫用
copyright © 萬盛學電腦網 all rights reserved