HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
PHP Keywords : Create a copy of an object
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.
Read more about classes in our PHP Classes and Objects Tutorial.
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);
?>
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);
?>
❮ PHP Keywords