Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Copy PHP Objects

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.

As shown by the two underscores beginning its name, the clone method is a different type of method, and thus is called differently, as shown in the following 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;
$firstCar->addGas(10);
$secondCar = clone $firstCar;

After these statements, you have two cars:

  • $firstCar: This car is red and contains ten gallons of gas. The ten gallons were added with the addGas method.

  • $secondCar: This car 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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.