Cloning nested objects
Lesson 41 of 48 in Coddy's PHP for Java Developers course.
This Java copy construction intentionally retains the nested reference. Java Object.clone is also shallow by default and requires its own access/Cloneable conventions. PHP clone is available through the language and calls __clone; nested object independence still requires 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.
Java program
import java.util.*;
class Main {
static class Leaf{int value=1;}
static class Tree{Leaf leaf;Tree(Leaf leaf){this.leaf=leaf;}}
public static void main(String[] args) throws Exception {
Leaf leaf=new Leaf();Tree a=new Tree(leaf);Tree b=new Tree(a.leaf);b.leaf.value=7;System.out.println(a.leaf.value);
}
}Source output:
7PHP 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:
7Challenge
EasyInput 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";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for Java Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batch8Sharing and identity
Traits reuse implementationObject handles and identityCloning nested objectsRecap: shared registryPractice on your own: Online PHP compiler