Cloning Objects
When you assign an object from one variable to another, you do not copy it, but merely assign a handle or reference to it.
<?php $a = new SomeClass(); $b = $a; // $a and $b point to the same underlying instance of SomeClass ?>
However, situations will arise where I'll actually want to assign a full copy of an existing object to a new variable. This is known as cloning, and is done via the clone operator.
<?php $a = new SomeClass(); $b = clone $a; // $b now is a NEW object with all the member variables set // to the values they had in $a ?>
When you clone an object in PHP, the language creates a new instance of the class and assigns copies of the corresponding variables in the original instance to this new object's member variables by default. However, this is a shallow copy, meaning that if one of those member variables is itself a reference to an object, only that reference is copied.
If the default behavior for cloning is not sufficient for your needs, you can implement the __clone function in your class, which PHP calls after it has performed the shallow copy of the member variables. If one of my member variables was a connection to a database, I might want to establish a new connection to the same database when my object is cloned.
<?php
class CloneDemo
{
public $dbconnection;
public $connect_string;
public function __clone()
{
// $connect_string is copied for us.
$this->dbconnection = $this->reestablish_connection(
$this->connect_string);
}
// etc.
}
?>
Now, whenever the object is cloned, the __clone method is called and the connection is also cloned.