Web EndMemo

PHP Clone



clone() copies an PHP object.
<?PHP
class colleague
{
	private $name;
	private $age;
	public $city;

	public function colleague($n="",$a=""){
		$this->name = $n;
		$this->age = $a;
		$this->city = "unknown";
	}
	
    public function __construct() {}	
    public function __destruct() {}		
}
$obj = new colleague("john","25");
var_dump($obj); //show contents of object $obj
$obj2 = clone $obj;
?>


If the class defined _clone() function, it will be executed while cloning:
<?PHP
class colleague
{
	private $name;
	private $age;
	public $city;

	public function colleague($n="",$a=""){
		$this->name = $n;
		$this->age = $a;
		$this->city = "unknown";
	}
	
    public function __construct() {}	
    public function __destruct() {}	

    public function __clone()
    {
	    this->name .= " copy";
	}	
}
$obj = new colleague("john","25");
//var_dump($obj); //show contents of object $obj
$obj2 = clone $obj;
echo "$obj->city, $obj2->city";
?>
The output is "unknown, unknown copy".