How to create a copy of an object in PHP?
Last Updated :
01 Dec, 2021
An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible). An object’s __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object’s properties. Any properties that are references to other variables will remain references.
Syntax:
$copy_object_name = clone $object_to_be_copied
Program 1: Program to create copy of an object.
php
<?php
class GFG {
public $data1 ;
public $data2 ;
public $data3 ;
}
$obj = new GFG();
$copy = clone $obj ;
$obj ->data1 = "Geeks" ;
$obj ->data2 = "for" ;
$obj ->data3 = "Geeks" ;
$copy ->data1 = "Computer " ;
$copy ->data2 = "science " ;
$copy ->data3 = "portal" ;
echo "$obj->data1$obj->data2$obj->data3\n" ;
echo "$copy->data1$copy->data2$copy->data3\n" ;
?>
|
Output:
GeeksforGeeks
Computer science portal
Example 2: Below program distinguishes clone from assignment ( = ) operator.
php
<?php
class GFG {
public $data1 ;
public $data2 ;
public $data3 ;
}
$obj = new GFG();
$copy = clone $obj ;
$obj_ref = $obj ;
$obj ->data1 = "Geeks" ;
$obj ->data2 = "for" ;
$obj ->data3 = "Geeks" ;
$copy ->data1 = "Python " ;
$copy ->data2 = "for " ;
$copy ->data3 = "Machine learning" ;
echo "$obj->data1$obj->data2$obj->data3\n" ;
echo "$copy->data1$copy->data2$copy->data3\n" ;
echo "$obj_ref->data1$obj_ref->data2$obj_ref->data3\n" ;
?>
|
Output:
GeeksforGeeks
Python for Machine learning
GeeksforGeeks
Note: It is clear that cloned object have different values than original object but original and referenced object created by using ‘=’ operator have same value.
References:https://www.php.net/manual/en/language.oop5.cloning.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...