중첩 객체 복제
Coddy의 C# 개발자를 위한 PHP 코스 레슨. 48개 중 41번째.
C#의 MemberwiseClone은 얕은 복사본을 만들며 중첩된 참조 필드를 공유 상태로 유지합니다. PHP의 clone도 __clone이 정책을 변경할 때까지 얕은 복사를 합니다. C#의 struct 필드는 값으로 복사되지만, 필드 자체에 참조가 들어 있을 수 있습니다. 따라서 변환할 때 class와 struct의 소유 관계를 고려해야 합니다.
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);
}
}소스 출력:
7PHP 프로그램
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챌린지
쉬움입력은 정수입니다. Cell에는 public int value가 있습니다. Box(Cell)에는 public Cell cell이 있습니다. Box::__clone():void는 중첩된 Cell을 복제하므로 복제된 상자의 값을 변경해도 원본에는 영향을 주지 않습니다. 드라이버는 복제한 다음 복제본의 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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러