Tuesday 25 May 2021

Php: __clone called while cloning an object

__clone method is called while cloning the object. __clone method is used to perform additional business logic while cloning an object.

 

How to define __clone method?

public function __clone(){

 

}

 

clone_method_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";
        }

        public function __clone(){
            echo "\nIn clone method\n";
        }

    }

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

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

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

?>

 

Output

$./clone_method_demo.php 

Inside constructor
id : 1
name: Krishna

Cloning the object

In clone method

cloned object details
id : 1
name: Krishna

 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment