- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a copy of an object in PHP?
To create a copy of an object in PHP, the code is as follows−
Example
<?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 "$ob->val1$ob->val2
"; echo "$copyOb->val1$copyOb->val2
"; ?>
Output
This will produce the following output−
JackKevin TomRyan
Example
Let us now see another example −
<?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); ?>
Output
This will produce the following output−
Demo Object( [deptname] => Finance [deptzone] => West ) Demo Object( [deptname] => Finance [deptzone] => West )
Advertisements