Menu
CoddyTech

克隆嵌套对象

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

C 语言中的结构体赋值会复制指针地址,因此复制后的外层结构体仍然会共享其指向的对象。PHP 的 clone 也是从浅拷贝开始的,如果定义了 __clone,则会调用它来进行有意的嵌套拷贝。你需要选择哪些协作对象应当保持共享,而不是盲目地复制每一个可达的对象。

clone 会对对象进行浅拷贝,如果定义了 __clone,则会调用它。标量属性会被复制,但嵌套的对象属性在被显式克隆之前仍保留共享标识符。请为需要独立性的字段实现克隆策略;对于共享服务或循环引用,递归复制所有内容可能是错误的。

C 程序

#include <stdio.h>
struct Inner{int value;};
struct Outer{struct Inner *inner;};

int main(void) {
struct Inner inner={2};struct Outer a={&inner};struct Outer b=a;b.inner->value=9;printf("%d:%d\n",a.inner->value,b.inner->value);
return 0;
}

源程序输出:

9:9

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,并打印 original:clone。

提供的主脚本从标准输入读取一个 JSON 值,检查指定的公开 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 在线编译器