Tuesday 25 May 2021

Php: clone an object

‘clone’ keyword is used to clone an object.

 

Syntax

$new_reference = clone $existing_reference;

 

When you execute clone statement, new object will be created by copying the property values of existing objects. Since these are two different objects, updating the original one will not affect cloned one and vice versa.

 

Will cloning calls __construct method?

No

 

clone_object_demo.php

#!/usr/bin/php

<?php

    class Employee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            echo "Inside constructor\n";
            $this->id = $id;
            $this->name = $name;
        }

        public function __toString() {
            return "id : $this->id\n". 
             "name: $this->name\n";
        }

    }

    $emp1 = new Employee(1, 'Krishna');
    $msg = (string)$emp1;
    echo $msg;

    $emp2 = clone $emp1;
    echo "\nCloning the object\n";
    $msg = (string)$emp2;

    $msg = (string)$emp2;
    echo "\ncloned object details\n $msg";

    echo "\n\nUpdating id and name of cloned object\n";
    $emp2->id = 2;
    $emp2->name='PTR';

    $msg = (string)$emp1;
    echo "emp1 details \n $msg\n";

    $msg = (string)$emp2;
    echo "\ncloned object details\n $msg\n";

?>

 

Output

$./clone_object_demo.php 

Inside constructor
id : 1
name: Krishna

Cloning the object

cloned object details
 id : 1
name: Krishna


Updating id and name of cloned object
emp1 details 
 id : 1
name: Krishna


cloned object details
 id : 2
name: PTR

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment