PHP 中以 雙下劃線 __ 開頭的類方法被視為魔術方法,在特定生命週期或操作觸發時自動調用。切勿在自定義方法中使用 __ 前綴,避免衝突。
| 方法 | 觸發時機 | 典型用途 |
|---|---|---|
__construct($args...) | 實例化 new Class() | 初始化屬性、依賴注入、資源獲取 |
__destruct() | 對象銷毀(引用計數歸零、腳本結束) | 釋放資源、關閉連接、寫入日誌 |
__clone() | clone $obj | 深拷貝資源、重置唯一標識 |
class PropertyDemo {
private $data = [];
public $publicProp = 'public';
public function __set($name, $value) {
echo "__set: 設置 '$name' = '$value'\n";
$this->data[$name] = $value;
}
public function __get($name) {
echo "__get: 讀取 '$name'\n";
return $this->data[$name] ?? null;
}
public function __isset($name) {
echo "__isset: 檢查 '$name'\n";
return isset($this->data[$name]);
}
public function __unset($name) {
echo "__unset: 刪除 '$name'\n";
unset($this->data[$name]);
}
}
$obj = new PropertyDemo();
$obj->a = 1; // __set
echo $obj->a; // __get -> 1
var_dump(isset($obj->a)); // __isset -> true
unset($obj->a); // __unset
var_dump(isset($obj->a)); // __isset -> false
class MethodDemo {
public function __call($name, $args) {
echo "__call: 物件調用 '$name' 參數: " . implode(', ', $args) . "\n";
}
public static function __callStatic($name, $args) {
echo "__callStatic: 靜態調用 '$name' 參數: " . implode(', ', $args) . "\n";
}
}
$obj = new MethodDemo();
$obj->run('foo', 'bar'); // __call
MethodDemo::run('foo', 'bar'); // __callStatic
__invoke() — 讓對象像函數一樣調用class CallableClass {
public function __invoke($x) {
var_dump($x);
}
}
$obj = new CallableClass();
$obj(5); // 直接調用對象,輸出 int(5)
var_dump(is_callable($obj)); // bool(true)
應用場景:策略模式、回調處理器、函數式編程風格。
__sleep / __wakeupclass User {
public $name;
public $token; // 敏感/臨時數據,不序列化
public function __construct($name) {
$this->name = $name;
$this->token = bin2hex(random_bytes(16));
}
public function __sleep() {
return ['name']; // 僅序列化 name
}
public function __wakeup() {
$this->token = bin2hex(random_bytes(16)); // 反序列化重新生成 token
}
}
$user = new User('Alice');
$ser = serialize($user); // 不包含 token
$restored = unserialize($ser); // token 重新生成
__toString() — 對象轉字符串class Entity {
public $id;
public function __toString() {
return "Entity#{$this->id}";
}
}
$e = new Entity(); $e->id = 42;
echo $e; // 輸出: Entity#42
__set_state() — var_export() 還原對象class Config {
public $host = 'localhost';
public $port = 3306;
public static function __set_state(array $props) {
$obj = new self();
foreach ($props as $k => $v) $obj->$k = $v;
return $obj;
}
}
$c = new Config(); $c->host = 'db.example.com';
eval('$c2 = ' . var_export($c, true) . ';'); // $c2 為新實例,屬性同步
__debugInfo() — var_dump() 輸出控制 (PHP 5.6+)class Secret {
public $password = '123456';
public $apiKey = 'sk_live_xxx';
public function __debugInfo() {
return [
'password' => '******',
'apiKey' => 'sk_live_***隱藏***',
];
}
}
var_dump(new Secret()); // 不會洩露真實敏感值
__serialize() / __unserialize() (PHP 7.4+)新一代序列化協議,替代 __sleep/__wakeup,支持類型化屬性、只讀屬性、無構造函數實例化,更安全、性能更好。
class Modern {
public string $name;
public readonly int $id;
public function __construct(string $name, int $id) {
$this->name = $name;
$this->id = $id;
}
public function __serialize(): array {
return ['name' => $this->name, 'id' => $this->id];
}
public function __unserialize(array $data): void {
$this->name = $data['name'];
$this->id = $data['id'];
}
}
| 魔術方法 | 觸發場景 | 返回值要求 | PHP 版本 |
|---|---|---|---|
| __construct | new Class() | 無 | 5.0+ |
| __destruct | 對象銷毀 | 無 | 5.0+ |
| __call | 對象調用不可見方法 | 混合 | 5.0+ |
| __callStatic | 靜態調用不可見方法 | 混合 | 5.3+ |
| __get/__set/__isset/__unset | 屬性重載 | 混合/無 | 5.0+ |
| __invoke | $obj() | 混合 | 5.3+ |
| __sleep | serialize() | array (屬性名列表) | 5.0+ |
| __wakeup | unserialize() | 無 | 5.0+ |
| __toString | (string)$obj / echo $obj | string | 5.0+ |
| __set_state | var_export() | object | 5.1+ |
| __debugInfo | var_dump() | array | 5.6+ |
| __serialize/__unserialize | serialize()/unserialize() | array/void | 7.4+ |