PHP 5 引入 __clone() 魔術方法,使物件複製行為可控。本文深入剖析克隆過程中 $this(副本)與 $that(原本)雙指標機制,並通過實例驗證屬性修改行為。
| 指標 | 指向 | 說明 |
|---|---|---|
$this | 副本(新物件) | 克隆操作產生的新實例 |
$that | 原本(原物件) | 被克隆的源實例 |
關鍵點:__clone() 在 新物件 上調用,$this 綁定新物件,$that 綁定舊物件。此設計允許在克隆瞬間差異化兩物件狀態。
<?php
class Person {
public $name;
public $sex;
public $age;
public function __construct($name, $sex, $age) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function say() {
echo "我的名字叫:{$this->name} 性別:{$this->sex} 我的年齡是:{$this->age}
";
}
public function __clone() {
// $this 指向副本 $p2,$that 指向原本 $p1
$this->name = "我是複製的張三 {$that->name}";
// $this->age = 30; // 可進一步修改其他屬性
}
}
$p1 = new Person("張三", "男", 20);
$p2 = clone $p1;
$p1->say(); // 原物件輸出
$p2->say(); // 副本輸出(經 __clone 修改)
?>
我的名字叫:張三 性別:男 我的年齡是:20
我的名字叫:我是複製的張三 張三 性別:男 我的年齡是:20
結果分析:
$p1 保持原狀:名字 "張三"$p2 經 __clone() 修改:名字變為 "我是複製的張三 張三"$that->name 讀取原物件屬性,$this->name 寫入新物件屬性class DatabaseConnection {
private $pdo;
public function __construct() {
$this->pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
}
public function __clone() {
// 重新建立資料庫連線,避免共享同一連線
$this->pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
}
}
class Entity {
public $id;
public $createdAt;
public function __clone() {
$this->id = null; // 新實體需重新分配 ID
$this->createdAt = time(); // 重設建立時間
}
}
$that 並非 PHP 內建變數,僅在 __clone() 內部可用。若在其他方法中使用會報錯「Undefined variable: that」。
__clone() 配合 $this/$that 雙指標,提供精細的物件複製控制能力。掌握此機制對實現原型模式、資源隔離、實體複製等進階設計模式至關重要。