Challenge - 5 Problems
PHP Clone Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of cloning with __clone method
What is the output of this PHP code when cloning an object with a __clone method that modifies a property?
PHP
<?php class Box { public $size; public function __construct($size) { $this->size = $size; } public function __clone() { $this->size *= 2; } } $box1 = new Box(5); $box2 = clone $box1; echo $box1->size . ',' . $box2->size; ?>
Attempts:
2 left
💡 Hint
Remember that __clone is called only on the cloned object, not the original.
✗ Incorrect
The original object keeps its size 5. The cloned object's __clone doubles its size to 10. So output is '5,10'.
🧠 Conceptual
intermediate1:30remaining
Effect of __clone on nested objects
If an object has a property that is another object, what happens to that nested object when the outer object is cloned using __clone?
Attempts:
2 left
💡 Hint
Think about shallow vs deep copy.
✗ Incorrect
By default, cloning an object copies its properties shallowly. Nested objects remain shared unless __clone explicitly clones them.
🔧 Debug
advanced2:30remaining
Why does cloning not duplicate nested objects?
Given this code, why does changing the nested object's property in the clone affect the original's nested object?
PHP
<?php class Inner { public $value; public function __construct($v) { $this->value = $v; } } class Outer { public $inner; public function __construct() { $this->inner = new Inner(10); } public function __clone() { // no cloning of inner } } $a = new Outer(); $b = clone $a; $b->inner->value = 20; echo $a->inner->value; ?>
Attempts:
2 left
💡 Hint
Check what __clone does with nested objects.
✗ Incorrect
The __clone method is empty, so the nested Inner object is not cloned. Both Outer objects share the same Inner instance, so changes affect both.
📝 Syntax
advanced1:30remaining
Identify the syntax error in __clone method
Which option contains a syntax error in the __clone method?
PHP
class Sample { public $data; public function __clone() { // code here } }
Attempts:
2 left
💡 Hint
Check the function declaration syntax carefully.
✗ Incorrect
Option A misses parentheses after __clone, causing a syntax error.
🚀 Application
expert3:00remaining
How to implement deep cloning with __clone
Given a class with multiple nested objects, how should you implement __clone to ensure a deep copy of all nested objects?
Attempts:
2 left
💡 Hint
PHP cloning is shallow by default.
✗ Incorrect
PHP only performs shallow cloning. To deep clone, you must manually clone each nested object inside __clone.