PHP Object Cloning

Object cloning is nothing but creating copy of an object. Object model is one of the popular feature in PHP 5. In this model, an object is passed by reference to create a copy of it where in PHP 4 it was passed by value.

download

cloning

Pass by Value

In this code we are copying object by passing its value to another variable. Using this method, if we make any change in the copy, it will affect the original object.

<?php
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"
print_r($objAnimals);
print_r($objCopied);
?>

When we change $objCopied it affects $objAnimals. The output is,

Values of object $objAnimals:
Animals Object
(
    [name] => Cat
    [category] => Pet Animal
)
Values of Copied object $objCopied:
Animals Object
(
    [name] => Cat
    [category] => Pet Animal
)

Object Cloning – Pass by Reference

In this example we are cloning objects by reference using PHP clone keyword. So, any changes made in cloned object will not affect original object.

<?php
//Creating instance of Animals class
$objAnimals = new Animals();
//Assigning values
$objAnimals->name = "Lion";
$objAnimals->category = "Wild Animal";
//Cloning the original object
$objCloned = clone $objAnimals;
$objCloned->name = "Elephant";
$objCloned->category = "Wild Animal";
print_r($objAnimals);
print_r($objCloned);
?>

Now we can see the difference in the output of this program.

Values of object $objAnimals:
Animals Object
(
    [name] => Lion
    [category] => Wild Animal
)
Values of Cloned object $objCopied:
Animals Object
(
    [name] => Elephant
    [category] => Wild Animal
)

download

This PHP code tutorial was published on April 11, 2013.

↑ Back to Top