PHP & MySQL® Web Development All-in-One Desk Reference for Dummies®
by Janet Valade, Tricia Ballad, Bill Ballad
4.8. Copying 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 10 gallons of gas. The 10 gallons were added with the addGas method.
$secondCar: This car is red, but contains 5 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 10 gallons of gas.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access