Skip to content

PHP 魔术方法:__clone

概述

__clone 魔术方法在对象被 clone 复制后自动调用,用于自定义复制行为,特别是实现深复制。

版本要求

  • __clone 在所有 PHP 5+ 版本中可用
  • PHP 8.3+:在 __clone 中可重新初始化 readonly 属性

基础概念

浅复制 vs 深复制

  • 浅复制(默认)clone 复制对象本身的属性值,但引用类型属性仍然指向原对象
  • 深复制:在 __clone 中手动复制引用类型属性,创建独立的副本

语法与代码

基本用法

php
<?php
declare(strict_types=1);

class Task
{
    public function __construct(
        public string $name,
        public array $tags = [],
    ) {}

    public function __clone()
    {
        // 深复制 tags 数组
        $this->tags = array_values($this->tags); // 创建新数组
    }
}

$original = new Task('Write docs', ['php', 'oop']);
$cloned = clone $original;

$cloned->name = 'Write tests';
$cloned->tags[] = 'testing';

echo $original->name; // Write docs
echo $cloned->name;    // Write tests

浅复制的问题

php
<?php
declare(strict_types=1);

class Profile
{
    public function __construct(
        public string $name,
        public \stdClass $meta,
    ) {}
}

$meta = new \stdClass();
$meta->level = 1;

$original = new Profile('Alice', $meta);
$cloned = clone $original;

$cloned->meta->level = 99;
echo $original->meta->level; // 99 — 共享同一个 meta 对象

深复制解决方案

php
<?php
declare(strict_types=1);

class Profile
{
    public function __construct(
        public string $name,
        public \stdClass $meta,
    ) {}

    public function __clone()
    {
        // 深复制 meta 对象
        $this->meta = clone $this->meta;
    }
}

$meta = new \stdClass();
$meta->level = 1;

$original = new Profile('Alice', $meta);
$cloned = clone $original;

$cloned->meta->level = 99;
echo $original->meta->level; // 1 — 独立的 meta 对象

详细说明

readonly 属性与 __clone(PHP 8.3+)

PHP 8.3 起可以在 __clone 中重新初始化 readonly 属性。

php
<?php
declare(strict_types=1);

class ImmutableEntity
{
    public readonly ?string $createdAt;
    public readonly int $version = 1;

    public function __construct()
    {
        $this->createdAt = date('Y-m-d H:i:s');
    }

    public function __clone()
    {
        // PHP 8.3+ 允许在 __clone 中修改 readonly 属性
        $this->createdAt = null;
        $this->version = $this->version + 1;
    }
}

$original = new ImmutableEntity();
echo $original->version; // 1

$cloned = clone $original;
echo $cloned->version;   // 2

clone 关键字

clone 创建对象的浅复制,然后调用 __clone 方法(如果定义了的话)。

php
<?php
declare(strict_types=1);

class Document
{
    public function __construct(
        public string $title,
        public array $content = [],
    ) {}

    public function __clone()
    {
        echo "Cloning document: {$this->title}\n";
    }
}

$doc1 = new Document('Report');
$doc2 = clone $doc1; // 输出: Cloning document: Report

实战示例

深复制包含嵌套对象的实体

php
<?php
declare(strict_types=1);

class Address
{
    public function __construct(
        public string $city,
        public string $street,
    ) {}
}

class Person
{
    public function __construct(
        public string $name,
        public Address $address,
        public array $phones = [],
    ) {}

    public function __clone()
    {
        $this->address = clone $this->address;
        $this->phones = array_map(
            fn(string $phone) => $phone,
            $this->phones,
        );
    }
}

$original = new Person(
    'Alice',
    new Address('Beijing', 'ChangAn'),
    ['13800138000'],
);

$cloned = clone $original;
$cloned->name = 'Bob';
$cloned->address->city = 'Shanghai';
$cloned->phones[] = '13900139000';

echo $original->address->city; // Beijing(不受影响)
echo $cloned->address->city;   // Shanghai

注意事项

  1. clone 是浅复制:引用类型属性共享同一实例
  2. __clone 在复制后调用:此时 $this 已是副本
  3. 不能阻止 clone:__clone 不能抛出异常来阻止复制(PHP 8+ 行为可能变化)
  4. private __clone 可以阻止外部 clone:但内部仍可 clone

最佳实践

  • 包含可变对象的类实现 __clone:确保深复制
  • readonly 属性在 PHP 8.3+ 可以在 __clone 中修改
  • 值对象通常不需要 __clone:不可变对象共享引用安全
  • __clone 中重新初始化所有可变状态

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接