Cloning objects

Once you have created an object, it is passed by reference when you pass it as a parameter.
 
In other words, making object assignments does not copy objects in their entirety. You’ll see how this works in Following Example, where we define a very simple User class with no methods and only the property name.

Example

<?php
$object1 = new User ();
$object1->name = "Alice";
$object2 = $object1;
$object2->name = "Amy";
echo "object1 name = " . $object1->name . "<br />";
echo "object2 name = " . $object2->name;
class User {
	public $name;
}
?>

We’ve created the object $object1 and assigned the value “Alice” to the name property. Then we create $object2, assigning it the value of $object1, and assign the value “Amy” just to the name property of $object2—or so we might think. But this code outputs the following:

Output

object1 name = Amy
object2 name = Amy

What has happened? Both $object1 and $object2 refer to the same object, so changing the name property of $object2 to “Amy” also sets that property for $object1. To avoid this confusion, you can use the clone operator, which creates a new instance of the class and copies the property values from the original class to the new instance.

Example

<?php
$object1 = new User ();
$object1->name = "Alice";
$object2 = clone $object1;
$object2->name = "Amy";
echo "object1 name = " . $object1->name . "<br>";
echo "object2 name = " . $object2->name;
class User {
	public $name;
}
?>

Output

object1 name = Alice
object2 name = Amy