PHP Objects and references


Introduction

In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value. It only contains an object identifier which allows using which the actual object is found. When an object is sent by argument, returned or assigned, the different variables are not aliases − instead, they hold a copy of the identifier, pointing to the same object.

Example

PHP has spl_object_hash() function that returns unique hash ID of an object. In following code, two object variables, referring to same object return same ID

Example

 Live Demo

<?php
class test1{
   public $name;
}
$obj1=new test1();
echo "ID of obj1: " . spl_object_hash($obj1) . "
"; $obj2=$obj1; echo "ID of obj2: " . spl_object_hash($obj2); ?>

Output

Result shows ID of both variables is same

ID of obj1: 000000004355dda6000000006f04b1a7
ID of obj2: 000000004355dda6000000006f04b1a7

When we create a reference of an object variable, by prefixing & to name, any changes in the properties are automatically reflected in reference variable

Example

 Live Demo

<?php
class test1{
   public $name;
}
$obj1=new test1();
echo "ID of obj1: " . spl_object_hash($obj1) . "
"; $obj2=&$obj1; echo "ID of obj2: " . spl_object_hash($obj2) . "
"; $obj1->name="Amar"; echo "name: " .$obj2->name; ?>

Output

Above code now returns name following output

ID of obj1: 00000000163cf0b8000000003ad0ed93
ID of obj2: 00000000163cf0b8000000003ad0ed93
name: Amar

Updated on: 18-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements