Cloning Objects in PHP

Cloning Objects:

An object copy is created by using the clone keyword (which calls the object's__clone() method if possible). An object's __clone() method cannot be called directly. $copy_of_object = clone $object; When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties.



class Animals


public $name;

public $category;


//Creating instance of Animals class

$objAnimals = new Animals();

//setting properties

$objAnimals->name = "Lion";

$objAnimals->category = "Wild Animal";

//Copying object

$objCopied = $objAnimals;

$objCopied->name = "Cat";

$objCopied->category = "Pet Animal";




Output: Animals Object ( [name] => Cat [category] => Pet Animal ) Animals Object ( [name] => Cat [category] => Pet Animal )

Custom Search

%d bloggers like this: