PHP 中物件預設為引用語意,$obj2 = $obj1 只是複製引用指標。clone 關鍵字建立物件的淺拷貝:新物件擁有獨立的屬性副本,但屬性值若為物件/資源,仍共享同一實例。__clone() 魔術方法在克隆完成後自動調用,用於自定義深拷貝邏輯。
<?php
class Address
{
public function __construct(public string $city, public string $street) {}
public function __toString(): string { return "$this->street, $this->city"; }
}
class User
{
public function __construct(
public string $name,
public Address $address,
public array $tags = []
) {}
}
$address = new Address('Taipei', 'Zhongxiao Rd');
$user1 = new User('Alice', $address, ['vip', 'early']);
$user2 = clone $user1; // 淺拷貝
// 修改基本型別屬性:不影響原物件
$user2->name = 'Bob';
echo $user1->name; // Alice ✅
// 修改物件屬性:共享同一 Address 實例!
$user2->address->street = 'Renai Rd';
echo $user1->address; // Renai Rd, Taipei ❌ 原物件被修改!
// 修改陣列屬性:COW 機制,修改時複製
$user2->tags[] = 'new';
echo implode(', ', $user1->tags); // vip, early (未受影響,COW 生效)
echo implode(', ', $user2->tags); // vip, early, new
?>
<?php
class User
{
public function __construct(
public string $name,
public Address $address,
public array $tags = [],
private ?User $referrer = null // 遞歸關聯
) {}
public function setReferrer(User $referrer): void
{
$this->referrer = $referrer;
}
// 克隆後自動調用
public function __clone()
{
// 1. 深拷貝物件屬性
$this->address = clone $this->address;
// 2. 陣列已是獨立副本 (COW),但若含物件需深拷貝
foreach ($this->tags as $key => $tag) {
if (is_object($tag)) {
$this->tags[$key] = clone $tag;
}
}
// 3. 遞歸關聯:決定是否克隆關聯物件
if ($this->referrer !== null) {
// 選項 A:克隆關聯 (完全隔離)
$this->referrer = clone $this->referrer;
// 選項 B:保持共享引用 (通常用於父實體)
// $this->referrer = $this->referrer;
// 選項 C:斷開關聯
// $this->referrer = null;
}
// 4. 重置/生成唯一標識
$this->id = 0; // 或生成新 UUID
}
}
// 使用
$addr = new Address('Taipei', 'Main St');
$user1 = new User('Alice', $addr);
$user1->setReferrer(new User('Admin', new Address('Sys', 'Root')));
$user2 = clone $user1;
$user2->name = 'Bob';
$user2->address->city = 'Kaohsiung';
echo $user1->address->city; // Taipei ✅ 獨立
echo $user2->address->city; // Kaohsiung
?>
<?php
function deepClone(object $object): object
{
// 限制:無法處理資源、Closure、循環引用、私有屬性需可序列化
return unserialize(serialize($object));
}
// 使用
$user2 = deepClone($user1);
?>
<?php
function deepCloneRecursive(object $object, array &$cloned = []): object
{
$splObjId = spl_object_id($object);
// 處理循環引用
if (isset($cloned[$splObjId])) {
return $cloned[$splObjId];
}
$reflection = new ReflectionClass($object);
$clone = $reflection->newInstanceWithoutConstructor();
$cloned[$splObjId] = $clone; // 先註冊再遞歸
foreach ($reflection->getProperties() as $prop) {
$prop->setAccessible(true);
$value = $prop->getValue($object);
if (is_object($value)) {
$value = deepCloneRecursive($value, $cloned);
} elseif (is_array($value)) {
$value = array_map(
fn($v) => is_object($v) ? deepCloneRecursive($v, $cloned) : $v,
$value
);
}
$prop->setValue($clone, $value);
}
// 調用 __clone 若存在
if ($reflection->hasMethod('__clone')) {
$clone->__clone();
}
return $clone;
}
?>
<?php
// composer require beberlei/assert ocramius/cloner
use Cloner\Cloner;
$cloner = new Cloner();
// 預設深拷貝所有物件屬性
$user2 = $cloner->cloneObject($user1);
// 進階配置
$cloner->addDelegate(
fn(DateTimeInterface $dt) => clone $dt, // DateTime 特殊處理
'DateTime'
);
$cloner->addPostCloneCallback(function(object $original, object $clone) {
// 克隆後回調:重置 ID、生成新 UUID 等
if (property_exists($clone, 'id')) {
$clone->id = 0;
}
});
?>
<?php
class Singleton
{
private static ?self $instance = null;
private function __construct() {}
public static function getInstance(): self
{
return self::$instance ??= new self();
}
// 禁止克隆
final public function __clone(): void
{
throw new Exception('單例模式禁止克隆');
}
// 禁止反序列化
public function __wakeup(): void
{
throw new Exception('單例模式禁止反序列化');
}
}
?>
<?php
class FileHandler
{
private $handle;
public function __construct(string $filename)
{
$this->handle = fopen($filename, 'r');
}
public function __clone()
{
// 資源無法直接 clone,需重新開啟
$meta = stream_get_meta_data($this->handle);
$this->handle = fopen($meta['uri'], 'r');
// 可選:恢復指標位置
fseek($this->handle, ftell($this->handle));
}
public function __destruct()
{
if (is_resource($this->handle)) fclose($this->handle);
}
}
?>
<?php
class Event
{
public function __construct(
public string $name,
public DateTimeImmutable $startTime // Immutable 不需克隆
) {}
// 若用 DateTime (可變),需在 __clone 中處理
public function __clone()
{
// DateTimeImmutable 不需處理,本身不可變
// 若是 DateTime: $this->startTime = clone $this->startTime;
}
}
?>
| 方法 | 耗時 | 記憶體 | 適用場景 |
|---|---|---|---|
| 手寫 __clone | 0.12s | 低 | 固定結構、高效能需求 |
| serialize/unserialize | 0.85s | 高 | 簡單物件、快速原型 |
| Reflection 遞歸 | 1.20s | 中 | 動態結構、未知類別 |
| ocramius/cloner | 0.15s | 低 | 生產環境、複雜物件圖 |
clone 只複製頂層屬性值spl_object_id() 追蹤已克隆物件DateTimeImmutable、Value Object 直接共享安全final __clone() 拋異常禁止克隆ocramius/cloner 處理邊緣情況物件克隆看似簡單,實則涉及淺/深拷貝、循環引用、資源管理、身份標識等複雜議題。手寫 __clone() 是最高效且可控的方案,配合不可變值物件設計,能將克隆邏輯降至最低。複雜物件圖推薦使用成熟庫 ocramius/cloner,並建立專案統一的克隆策略規範。