$ this-> myObject = clone $ this-> myObject;
I have a question about cloning objects in PHP. I understand that a clone creates a "deep copy" in that a new object is created with its variables, initialized with the values โโof the corresponding variables in the object from which it was cloned. However, as described here , this means that any referenced variables will reference the same value, likely creating problems.
The book I am reading has the following solution similar to the one above:
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 it as best I could, I can't get my head around what's going on with this line:
$this->refObj = clone $this->$refObj;
Any light anyone can shed will be of immense help.
source to share
Good question.
The line you pointed out clones the referenced objects, so avoid the double pointer problem.
Hence, the method _clone
not only clones the object itself, but all the objects to which it refers.
For example, if you had a car object id 1 that had a reference to the engine object id 1, after the clone you would have a new car identified by 2 and a new engine identified by 2. Without the extension _clone
, you would have a car identified by 2 referencing to the engine identified by 1.
Note that the magic clone is only needed for objects with non-primitive types as attributes.
source to share