How to create a copy of an object in PHP?

PHPServer Side ProgrammingProgramming

To create a copy of an object in PHP, the code is as follows−

Example

 Live Demo

<?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\n";
   echo "$copyOb->val1$copyOb->val2\n";
?>

Output

This will produce the following output−

JackKevin
TomRyan

Example

Let us now see another example −

 Live Demo

<?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
)
raja
Published on 26-Dec-2019 10:32:08
Advertisements