PHP __clone() method

PHP __clone() method is used to create a copy of an object. Objects are always passed by reference or address in Copy Constructor using __clone() method.

Copy Constructor will pass the address of the other objects as a parameter.

Syntax :

$copy_object = clone $object;

 

Example :

<?php
class copyConstructor {
public $name;

public function __construct($name){ // parameterized constructor with name argument
$this->name = $name;
echo "<br>Inside parameterized constructor<br>";
}
public function __clone(){
echo "<br>Inside copy constructor<br>";
}
}
$obj1 = new copyConstructor ("aryatechno"); // parameterized constructor with name argument
$obj2= clone $obj1; // copy constructor initialize $obj2 with the values of $obj1
echo "<br/>Value from parameterized constructor : ".$obj1->name;
echo "<br/>Value from copy constructor : ".$obj2->name;
?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

40641