class Test {
function __construct() { echo "before"; }
}
$t = new Test(); // 輸出:before
若同時定義同名方法 function Test(),PHP 5 優先調用 __construct()。
class Test {
function __destruct() { echo "end"; }
}
$t = new Test(); // 腳本結束或 unset($t) 時輸出:end
適用於釋放資源、關閉連接、寫入日誌。
class Test {
public function __get($key) { echo "$key 不存在"; }
}
$t = new Test();
echo $t->name; // 輸出:name 不存在
class Test {
public function __set($key, $value) { echo "對 $key 附值 $value"; }
}
$t = new Test();
$t->name = "aninggo"; // 輸出:對 name 附值 aninggo
class Test {
public function __call($method, $args) {
echo "您要調用的 {$method} 方法不存在。參數:" . print_r($args, true);
}
}
$t = new Test();
$t->getName('aning', 'go');
/* 輸出:
您要調用的 getName 方法不存在。參數:
Array ( [0] => aning [1] => go )
*/
class Test {
public function __toString() { return "打印 Test"; }
}
$t = new Test();
echo $t; // 輸出:打印 Test
class Test {
public function __clone() { echo "我被復制了!"; }
}
$t = new Test();
$t1 = clone $t; // 輸出:我被復制了!
可在克隆時深拷貝資源、重置標識符等。
__construct/__destruct 替代舊式同名構造/解構方法。__get/__set 配合 private 屬性實現屬性訪問控制、懶加載、數據驗證。__call 用於動態代理、方法別名、AOP 攔截。__toString 讓對象直接參與字符串拼接、日誌輸出。__clone 確保克隆對象狀態獨立(如複製資源句柄、生成新 ID)。