Copying Objects

chinmay.sahoo

New member
PHP provides a method you can use to copy an object. The method is __clone,with two underscores. You can write your own __clone method in a class if you want to specify statements to run when the object is copied. If you don’t write your own, PHP uses it’s default __clone method that copies all the properties as is. The two underscores indicate that the clone method is a different type of method, and thus is called differently, as shown in the following example .

For example, you could write the following class:

class Car
{
private $gas = 0;
private $color = “red”;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
function __clone()
{
$this->gas = 0;
}
}

Using this class, you could create an object and copy it as follows:

$firstCar = new Car;
$firstCar->addGas(10);
$secondCar=clone $firstCar;

After these statements, you have two cars:

 $firstCar: This car is red and contains 10 gallons of gas. The 10 gallons were added with the addGas method.
 $secondCar: This car is red, but contains 0 gallons of gas. The duplicate car is created using the __clone method in the Car class. This method sets gas to 0 and doesn’t set $color at all.

If you did not have a __clone method in the Car class, PHP would use a default __clone method that would copy all the properties, making $secondCar both red and containing 10 gallons of gas.
 
Back
Top