Menu
CoddyTech

Cloning nested objects

Lesson 41 of 48 in Coddy's PHP for Ruby Developers course.

Ruby dup is shallow; nested hashes remain shared here. Ruby clone also carries details such as frozen state differently from dup. PHP clone preserves the class and invokes __clone, but nested objects remain shared unless explicitly cloned. Ruby hashes and PHP arrays have different assignment semantics.

clone makes a shallow copy of an object, then invokes __clone if defined. Scalar properties are copied, but nested object properties still hold shared identifiers until explicitly cloned. Implement a clone policy for the fields that need independence; copying everything recursively may be wrong for shared services or cycles.

Ruby program

leaf = {value: 1}
a = {leaf: leaf}
b = a.dup
b[:leaf][:value] = 7
puts a[:leaf][:value]

Source output:

7

PHP program

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 output:

7
challenge icon

Challenge

Easy

Input is an integer. Cell has public int value. Box(Cell) has public Cell cell. Box::__clone():void clones the nested Cell so changing a cloned box does not affect original. Driver clones then sets clone cell value to nine, printing original:clone.

The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.

Edit Cell.php, Box.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.

Try it yourself

<?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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PHP for Ruby Developers

Practice on your own: Online PHP compiler