萬盛學電腦網

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

PHP 魔術方法實戰:__autoload、__clone、__toString、__call 完整解析

常用自動呼叫魔術方法

方法觸發時機典型用途
__autoload($class)使用未定義類別時自動載入類別檔案 (已棄用,改用 spl_autoload_register)
__clone()clone $obj 後深層複製、重設資源 ID、生成新唯一識別碼
__toString()物件當字串用時友善輸出、除錯顯示、模板渲染
__call($name, $args)呼叫不可存取方法動態方法、委派、Proxy 模式
__callStatic($name, $args)靜態呼叫不可存取方法動態靜態方法、ActiveRecord 查詢

__toString() 範例

class User {
    public $name, $email;
    public function __construct($name, $email) {
        $this->name = $name; $this->email = $email;
    }
    public function __toString() {
        return "User: {$this->name} <{$this->email}>";
    }
}
$user = new User("張三", "zhang@example.com");
echo $user; // 直接輸出物件,自動呼叫 __toString()
// User: 張三 <zhang@example.com>

__clone() 深層複製

class User {
    public $name;
    public $address; // 另一個物件
    
    public function __construct($name, Address $address) {
        $this->name = $name;
        $this->address = $address;
    }
    
    public function __clone() {
        // 深層複製 address 物件
        $this->address = clone $this->address;
        // 重設唯一識別碼
        $this->id = uniqid();
    }
}

$addr = new Address("台北市", "信義路");
$user1 = new User("張三", $addr);
$user2 = clone $user1; // 觸發 __clone
$user2->name = "李四";
$user2->address->city = "高雄市";
// $user1->address->city 仍為 "台北市" (深層複製生效)

__call() 動態方法

class Database {
    private $pdo;
    
    public function __call($method, $args) {
        // 動態處理 findByXxx, findAllByXxx
        if (preg_match('/^find(By|AllBy)(.+)/', $method, $matches)) {
            $fields = explode('And', $matches[2]);
            // 建構 SQL 查詢...
            return $this->query($sql, $args);
        }
        throw new BadMethodCallException("方法 $method 不存在");
    }
}

$db = new Database();
$users = $db->findByNameAndEmail("張三", "zhang@example.com");

__autoload 現代替代:spl_autoload_register

// 註冊多個自動載入器,依序嘗試
spl_autoload_register(function ($class) {
    $file = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) require_once $file;
});

spl_autoload_register(function ($class) {
    $file = __DIR__ . '/lib/' . str_replace('_', '/', $class) . '.php';
    if (file_exists($file)) require_once $file;
});

// 專案實務:直接用 Composer
require_once __DIR__ . '/vendor/autoload.php';

其他實用魔術方法

  • __invoke():讓物件可像函數呼叫 $obj()
  • __sleep() / __wakeup():序列化控制(敏感資料排除、資源重連)
  • __set_state():var_export() 匯出支援
  • __debugInfo():自訂 var_dump() 輸出
copyright © 萬盛學電腦網 all rights reserved