Reputation: 1108
I have a question regarding object cloning in PHP. I understand that clone creates a "deep copy" in that a new object is created with its variables initialized to the values of the corresponding variables in the object from which it is cloned. However, as discussed here, this means that any reference variables will be references to the same value, likely creating issues.
The book I'm reading gives the following solution, similar to the one given at the above link:
class ReferenceClass {
public $msg = 'Reference Object';
}
class CloneClass {
public $refObj;
public function __construct() {
$this->refObj = new ReferenceClass();
}
public function __clone() {
$this->refObj = clone $this->$refObj;
}
}
However, try as I might, I can't wrap my head around what's happening with this line:
$this->refObj = clone $this->$refObj;
Any light anyone may be able to shed will be a huge help.
Upvotes: 3
Views: 94
Reputation: 1268
Good question.
The line that you've pointed out is cloning the referenced objects, therefore avoiding double-pointer issues.
Hence, the _clone
method does not only clone the object itself, but also all it's referenced objects.
For example, if you had a car object of id 1 which had a reference to an engine object of id 1, after the clone you will have a new car identified by 2 and a new engine identified by 2.
Without the _clone
extension, you would have had a car identified by 2 referencing an engine identified by 1.
Please note, magic clone is only required for objects with non-primitive types as attributes.
Upvotes: 2