Table of Contents
Introduction
In PHP, objects are always passed by reference. This means that when we pass an object into a function, any changes we make to it in there are reflected outside the function.
However, it is sometimes important to only work on copies of objects - you might not want to affect the state of the original. To do this, we use the keyword clone
, which results in a complete copy of the object.
Copying an Object
Example
Copying an object via assignment. 1<?php
2 $person_A = new User();
3 $person_A->name = "Jimmy";
4
5 $person_B = $person_A; // copying
6 $person_B->name = "Joe";
7
8 echo "person_A name = " . $person_A->name . "<br>";
9 echo "person_B name = " . $person_B->name;
10
11 class User
12 {
13 public $name;
14 }
15?>
person_A name = Joe
person_B name = Joe
In this example,
- we first create the object
$person_A
and assign the value ‘Jimmy’ to the$name
property. - Then we assign
$person_A
to$person_B
. - We initialize the
$name
property of$person_B
to the value of ‘Joe’.
When we print the $name
property of both objects, we discover the same value Joe
is printed in both cases.
In this example, both $person_A
and $person_B
refer to the same object in memory (as per the assignment operator) . When we change the property of one of them, it is reflected in both objects.
Cloning an Object
To avoid the above confusion, we can use the clone
operator, which creates a new instance of the class and copies the property values from the original instance to the new instance.
Example
Cloning an object. 1<?php
2 $person_A = new User();
3 $person_A->name = "Jimmy";
4
5 $person_B = clone $person_A; // cloning
6 $person_B->name = "Joe";
7
8 echo "person_A name = " . $person_A->name . "<br>";
9 echo "person_B name = " . $person_B->name;
10
11 class User
12 {
13 public $name;
14 }
15?>
person_A name = Jimmy
person_B name = Joe