Site icon DataFlair

Object Cloning in PHP

Program 1

<html>
<head><title>Demo</title></head>
<body>
    <center>
    <?php
    class Employee
    {
         public $empname;
         public $department;  // sub object of department class
         public function __construct($ename,$d1)
         {
             $this->empname=$ename;
             $this->department=$d1;
         }
             public  function __clone()
             {
                echo "<br><font color=red>***********This clone function***************</font><br>";
                   $this->department=clone $this->department;
             }         
    }
    class department
    {
           public $deptname;
           public function __construct($dname)
           {
               $this->deptname=$dname;
           }
          
    }
    $dt=new department('CSE');
    $e1=new Employee('Vivek',$dt);

    

    $e2=clone $e1;

    print_r($e1);
    echo "<br>";
    print_r($e2);

    $e2->empname='Rajesh';
    $dt->deptname='Civil';
    echo "<br>--------After Change-----------------<br>";
    print_r($e1);
    echo "<br>";
    print_r($e2);
?>
</center>
</body>
</html>

 

Exit mobile version