In simple words 'object cloning' can be defined as copying the object property and assigning to a different object. But when we copy an object then it only owns the reference, not the value.
In PHP this is done by two method-
1) By using clone Keyword-
In this, a shallow copy of the object is made. It means the internal object of the objectA is not cloned to the internal object of objectB.
class CloneableClass { private $_internalObject; public function __construct() { // instantiate the internal member $this->_internalObject = new stdClass(); } } $objectA = new CloneableClass(); $objectB = clone $objectA;
2) By using __clone() method-
if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
In this the magic method __clone() is used to clone internal object or the referenced one. So objectB will be the exact copy of the objectA.
class CloneableClass
{
private $_internalObject;
public function __construct()
{
// instantiate the internal member
$this->_internalObject = new stdClass();
}
// on clone, make a deep copy of this object by cloning internal member;
public function __clone()
{
$this->_internalObject = clone $this->_internalObject;
}
}
$objectA = new CloneableClass();
$objectB = clone $objectA;
Comments
Post a Comment