oursolutionarchitectoursolutionarchitect

PHP Object Cloning


Definition and Usage

The clone keyword is used to create a copy of an object.

If any of the properties was a reference to another variable or object, then only the reference is copied. Objects are always passed by reference, so if the original object has another object in its properties, the copy will point to the same object. This behavior can be changed by creating a __clone() method in the class.


Related Pages

Read more about classes in our PHP Classes and Objects Tutorial.


More Examples

Example

Create a copy of an object which has a reference:

<?php
class MyClass {
  public $amount;
}

// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;

// Clone the object
$copy = clone $obj;

// Change the value in the original object
$obj->amount = 6;

// The copy is changed
print_r($copy);
?>
Try it Yourself »

Example

Use a __clone() method to break references in a copied object:

<?php
class MyClass {
  public $amount;
  public function __clone() {
    $value = $this->amount;
    unset($this->amount); // Unset breaks references
    $this->amount = $value;
  }
}

// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;

// Clone the object
$copy = clone $obj;

// Change the value in the original object
$obj->amount = 6;

// The copy is not changed
print_r($copy);
?>