How to Clone an Object in PHP 


               


How to Clone an Object in PHP

php


In this article, we go over how to clone an object in PHP.

When you clone an object, you create a new object with all the same properties as the original object.

There are many reasons why you would want to clone an object in PHP.

Imagine you have a class named cars that represent car objects.

Now imagine a car object has several properties such as car type, the year of the car, the year of the car, the color of the car, whether it's automatic or manual, what condition it is, etc. In other words, a long list of properties.

Imagine it's a car salesman who's keeping a list of these cars in programming. Imagine now that another car comes to the lot. It's the same exact car as one you have. Instead of creating a new object from scratch and filling in all the properties, it would far easier and quicker just to clone the car that's the exact copy. That way, all the properties are copied or cloned onto the new created object.

And it doesn't even have to be an exact copy.

For example, everything could be the same, the color, car type, automatic engine, except the year is different. In this case, you close the orignal object and just change the year property.

So cloning an object can be a great, quick solution when all or most of the properties are the same as the orignal object.

It provides for less coding.

So below in the PHP code is the general code to clone an object.



So in the above code, we have created an object, $car2, which is a clone of $car1.

So $car2 has all of the properties of $car1.

We show the full PHP code so you can this demonstrated.



So in the above code, we've created a class named cars.

We then create an instance (or object) of this class named $car1.

We assign this $car1 object properties, such as the type, year, color, and engine type.

The $car1 object is a 2015 Toyota Camry that is a green and has an automatic engine.

We then create a new object, $car2, and set this equal to clone $car1. Thus, $car2 is a clone of $car1.

We then modify the year property of the $car2 object. We change the year to 2014.

So the $car2 object is the same as the $car1 object, except $car2 is a 2014, not 2015.

This still saved us a lot of time, because we didn't have to write out all the properties again. All we had to do was change the year property.

So this is all that is needed to clone an object of a class in PHP.

Going back to the PHP code above, if it's run, this gives the following output shown below.

Actual PHP Output


Car 1: Toyota Camry 2015 Green Automatic
Car 2: Toyota Camry 2014 Green Automatic


HTML Comment Box is loading comments...