Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a copy of an object in PHP?
In PHP, you can create a copy of an object using the clone keyword. This creates a shallow copy of the object, copying all properties to a new instance while maintaining the same values.
Basic Object Cloning
The simplest way to copy an object is using the clone keyword −
<?php
class Demo {
public $val1;
public $val2;
}
$ob = new Demo();
$copyOb = clone $ob;
$ob->val1 = "Jack";
$ob->val2 = "Kevin";
$copyOb->val1 = "Tom";
$copyOb->val2 = "Ryan";
echo "Original: " . $ob->val1 . " " . $ob->val2 . "<br>";
echo "Copy: " . $copyOb->val1 . " " . $copyOb->val2 . "<br>";
?>
Original: Jack Kevin Copy: Tom Ryan
Cloning Objects with Constructor
You can also clone objects that have constructors. The clone will preserve the initialized values −
<?php
class Demo {
public $deptname;
public $deptzone;
public function __construct($a, $b) {
$this->deptname = $a;
$this->deptzone = $b;
}
}
$val = new Demo('Finance', 'West');
$copy = clone $val;
print_r($val);
print_r($copy);
?>
Demo Object
(
[deptname] => Finance
[deptzone] => West
)
Demo Object
(
[deptname] => Finance
[deptzone] => West
)
Key Points
| Feature | Description |
|---|---|
| Shallow Copy | Creates new object with same property values |
| Independence | Original and copy are separate instances |
| Property Changes | Modifying one object doesn't affect the other |
Conclusion
Use the clone keyword to create object copies in PHP. The cloned object becomes an independent instance with the same property values as the original.
Advertisements
