Menu
CoddyTech

Cloning nested objects

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

JavaScript object spread makes a shallow copy of own enumerable properties and does not preserve a class prototype as a cloning operation. PHP clone preserves the object class but is also shallow for nested objects until __clone applies an explicit policy.

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.

JavaScript program

const a={leaf:{value:1}}; const b={...a}; b.leaf.value=7; console.log(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 JavaScript Developers

Practice on your own: Online PHP compiler