How to Copy Objects of Class

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 its default __clone method that copies all the properties as is.

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 = 5;

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

$firstCar = new Car;
$secondCar = clone $firstCar;

After these statements, you have two cars:

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

If you didn’t 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 ten gallons of gas.

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive