Wednesday 26 May 2021

Php: Object are assigned by reference

In Php, objects are always assigned by reference (It is not the same case with normal variables).

 

For example, Let’s create an Employee object.

$emp1 = new Employee(1, 'krishna');

 


Let’s assign $emp1 to $emp2.

$emp2 = $emp1;


 

As shown in the above image, both $emp1 and $emp2 points to the same memory location. Whatever the changes you are done via $emp2 will be reflected to $emp1 and vice versa.

 

Find the below working application.

 

assignment_by_reference_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 about_me($name){
            echo "\n\n$name details:\n";
            echo $this->__toString();
        }

    }

    $emp1 = new Employee(1, 'krishna');
    $emp2 = $emp1;

    $emp1->about_me('emp1');
    $emp2->about_me('emp2');

    echo "\nUpdating the name property using the reference emp2\n";

    $emp2->name='Shankar';
    $emp1->about_me('emp1');
    $emp2->about_me('emp2');


?>


Output

$./assignment_by_reference_demo.php 

Inside constructor


emp1 details:
id : 1
name: krishna


emp2 details:
id : 1
name: krishna

Updating the name property using the reference emp2


emp1 details:
id : 1
name: Shankar


emp2 details:
id : 1
name: Shankar









Previous                                                    Next                                                    Home

No comments:

Post a Comment