Menu
CoddyTech

克隆嵌套对象

Coddy 面向 C# 开发者的 PHP 课程的第 41 课,共 48 课。

C# 的 MemberwiseClone 会创建浅拷贝,并让嵌套的引用字段保持共享。PHP 的 clone 同样是浅拷贝,除非 __clone 更改了这一行为。C# 结构体字段会按值复制,但字段本身也可能包含引用;进行转换时,必须考虑类和结构体的所有权差异。

clone 会创建对象的浅拷贝,然后在定义了 __clone 时调用它。标量属性会被复制,但嵌套对象属性仍然持有共享的标识,除非显式克隆它们。为需要独立的字段实现克隆策略;递归复制所有内容可能并不合适,例如字段引用共享服务或存在循环引用时。

C# 程序

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
class Leaf{public int Value=1;}
class Tree{public Leaf Leaf;public Tree(Leaf leaf){Leaf=leaf;}public Tree Copy(){return (Tree)MemberwiseClone();}}
 static void Main() {
  var a=new Tree(new Leaf());var b=a.Copy();b.Leaf.Value=7;Console.WriteLine(a.Leaf.Value);
 }
}

源代码输出:

7

PHP 程序

Leaf.php

<?php
declare(strict_types=1);
class Leaf {public int $value=1;}

Tree.php

<?php
declare(strict_types=1);
require_once __DIR__."/Leaf.php";class Tree {public function __construct(public Leaf $leaf){}}

demo.php

<?php
declare(strict_types=1);
require_once __DIR__."/Tree.php";$a=new Tree(new Leaf());$b=clone $a;$b->leaf->value=7;echo $a->leaf->value,"\n";

PHP 输出:

7
challenge icon

挑战

简单

输入是一个整数。Cell 有 public int value。Box(Cell) 有 public Cell cell。Box::__clone():void 会克隆嵌套的 Cell,因此更改克隆后的 Box 不会影响原对象。驱动程序会克隆对象,然后将克隆对象的 cell 值设为 9,并打印原对象:克隆对象。

提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的 public API,并打印结果。实现模块声明时不要打印内容;不要替换启动脚本,也不要在模块中读取输入。输入符合所述类型和范围。

编辑 Cell.php、Box.php。main.php 是锁定的入口文件。依赖项使用带相对文件名的 require_once __DIR__。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Cell.php";
require_once __DIR__."/Box.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function boxReport(int $n):string{$a=new Box(new Cell($n));$b=clone $a;$b->cell->value=9;return $a->cell->value.":".$b->cell->value;}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new Box(new Cell(6));$b=clone $a;ensure($a!==$b && $a->cell!==$b->cell,"nested isolation");$b->cell->value=2;ensure($a->cell->value===6,"original unchanged");
echo boxReport($input),"\n";
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 PHP中的所有课

自己练习: PHP 在线编译器