1.2.1107. Should Deep Clone¶
By default, PHP makes a shallow clone. It only clone the scalars, and keep the reference to any object already referenced. This means that the cloned object and its original share any object they hold as property.
This is where the magic method __clone() comes into play. It is called, when defined, at clone time, so that the cloned object may clone all the needed sub-objects.
It is recommended to use the __clone() method whenever the objects hold objects.
<?php
class a {
public $b = null;
function __construct() {
$this->b = new Stdclass();
$this->b->c = 1;
}
}
class ab extends a {
function __clone() {
$this->b = clone $this->b;
}
}
// class A is shallow clone, so $a->b is not cloned
$a = new a();
$b = clone $a;
$a->b->c = 3;
echo $b->b->c;
// displays 3
// class Ab is deep clone, so $a->b is cloned
$a = new ab();
$b = clone $a;
$a->b->c = 3;
echo $b->b->c;
// displays 1
?>
See also PHP Clone and Shallow vs Deep Copying and Cloning objects.
1.2.1107.1. Connex PHP features¶
1.2.1107.1.1. Specs¶
Short name |
Classes/ShouldDeepClone |
Rulesets |
|
Exakat since |
1.7.0 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |