Understanding the PHP Clone Method and Its Usage

Understanding the php clone method and its usage

When writing your own PHP code you'll either be doing that procedurally or in an object-oriented manner. Code written in an object-oriented style will have classes and objects that will perform their own tasks. Code in a procedural style won't typically have this and is normally restricted to single file script and/or create code duplication. If you haven't already, writing code in an object-oriented way not only increases code reusability but is easier to scale.

What is Object-Oriented Programming?

A programming paradigm known as object-oriented programming (OOP) centres on the idea of objects, which are instances of classes. Data and action are arranged into objects in object-oriented programming. Objects can inherit from their parent classes' attributes and methods, and classes define the properties and methods that an object may have. By enabling developers to build code that is organised around objects and their relationships, OOP increases code modularity. OOP is supported by a number of well-known programming languages, including Python, C++, Java, and of course PHP.

When in an object-oriented style of programming, cloning refers to the process of creating a copy of an object. In PHP, the clone keyword is used to create a clone of an object. This method creates a new object with the same properties as the original object.

What does the clone keyword do in PHP?

Clone is a built-in keyword in PHP that allows you to create a copy of an object. When you clone an object, PHP creates a new object with the same properties as the original object. Once called, if the object has the function __clone() that will also be called. This is called once the object cloning has been completed. That means you can if you wish allow for any properties to be changed at the point of clone. Once cloned the new object will exist in its own memory space, which means changes to this new object aren't received and don't affect the original object (that you cloned).

When you clone an object, any objects that reference are also cloned, known as deep cloning. This ensures that all properties and sub-objects are also copied over to the newly formed object. The example code below shows clone in action, cloning "$object" to a new object called "$clondedObject".

$clonedObject = clone $object;

If the object you are cloning has the __clone function, that will also be called, like the example class below.

class TestObject
{
 public function __clone() {
 //...
 }
}

Let's explore a full example of how clone works in PHP. Below we have a class called 'Animal', and that contains the construct and a function called 'whoAreYou'. When you clone "Animal" the cloning process will copy these functions too as well as the name and type properties. Next, the code sets the animal as named 'Bob' and of type 'Cat'. Once set, if we clone to a new object in this case '$dog', this will carry over the exact same state of '$cat'. With our new object, we can as we did with '$cat', set the name and type. We also, set 'Rover' and 'Dog' and the two property values. Next, we clone '$dog' into a new object called '$snake'. However, this time we do not set the name, only the type and the result is rather assuming. "Snake called Rover". That's because we didn't set the name, and therefore it used the original objects' property value 'Rover'.

class Animal {
 public $name;
 public $type;

 public function __construct($name, $type) {
 $this->name = $name;
 $this->type = $type;
 }

 public function whoAreYou() {
 echo $this->type. " called " . $this->name;
 }
}

$cat = new Animal("Bob", "Cat");

# Clone object
$dog = clone $cat;

$dog->name = "Rover";
$dog->type = "Dog";

# Clone object
$snake = clone $dog;
$snake->type = "Snake";

# Outputs: Cat called Bob
$cat->whoAreYou();

# Outputs: Dog called Rover
$dog->whoAreYou();

# Outputs: Snake called Rover
$snake->whoAreYou();

If we now add the magic method __clone() to our class, we can use this to perform actions after the clone we could set additional text to our properties. In the example below, if we don't set the name on the object clone, the magic method __clone() is called and will append "(we think)" to the name. As '$snake' didn't set a name itself, this is the object that will call it. It's good practice to set magic methods as public, even though __clone doesn't have to be, in PHP 8 and above any non-public magic methods are deprecated. It's also important to note that unless you're overriding PHP's behavior other methods you use don't start with '__' (double underscore).

# Outputs: Snake called Rover (we think)

public function __clone() {
 $this->name = $this->name . " (we think)";
}

With PHP it is also possible to clone in a single-line expression, like the example below. Here we clone '$cat' and straight away call 'whoAreYou' function. It's important you wrap the clone part in brackets otherwise you might trigger a fatal error "Uncaught Error: __clone method called on non-object".

# Outputs: Cat called Bob
(clone $cat)->whoAreYou();

There are a number of reasons why you might wish to clone in PHP. Firstly, if you wish to preserve the original objects, working with a copy of it is better by cloning it without affecting the object you want to protect. Secondly, for performance reasons, it's generally quicker to clone than create a new object, and then set properties, in cases where the two objects are nearly identical. Finally, for object composition reasons. In some use cases, you may create an object that contains other objects as properties, and cloning allows you to create a copy and nested objects when working with complex object hierarchies. Nested data structures or object factories would be some examples of this.

Conclusion

Object cloning in PHP is a great way to quickly and easily copy one object's properties to another. Creating a separate instance is a good way to protect the original object from getting changed and allows you to become more flexible and create better and more powerful object-oriented applications.

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all