The object model in PHP5 calls objects by reference, but sometimes you may want to create a copy of the object and hope that changes to the original object will not affect the copy. For this purpose, PHP defines an extraordinary method, Called __clone. Like __construct and __destruct, there are two underscores in front.
By default, using the __clone method will create an object with the same properties and methods as the original object. If you want to change the default content when cloning, you have to override (properties or methods) in __clone.
The clone method can take no parameters, but it contains both this and that pointers (that points to the object being copied). If you choose to clone yourself, you need to be careful to copy any information you want your object to contain from that to this. If You use __clone to copy. PHP does not perform any implicit copying,
The following shows an example of automating objects using series ordinal numbers:
class ObjectTracker file://Object Tracker
{
private static $nextSerial = 0;
private $id;
private $name;
function __construct($name) file://constructor
{
$this->name = $name;
$this->id = self::$nextSerial;
}
function __clone() file://clone
{
$this->name = "Clone of $that->name";
$this->id = self::$nextSerial;
}
function getId() file://Get the value of the id attribute
{
return($this->id);
}
function getName() file://Get the value of the name attribute
{
return($this->name);
}
}
$ot = new ObjectTracker("Zeev's Object");
$ot2 = $ot->__clone();
//Output: 1 Zeev's Object
print($ot->getId() . " " . $ot->getName() . "
");
//Output: 2 Clone of Zeev's Object
print($ot2->getId() . " " . $ot2->getName() . "
");
?>