Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Objects and references
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 access to the actual object. 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.
Object Assignment
PHP has spl_object_hash() function that returns unique hash ID of an object. In the following code, two object variables referring to the same object return the same ID ?
<?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);
?>
The output shows that both variables point to the same object ?
ID of obj1: 000000004355dda6000000006f04b1a7 ID of obj2: 000000004355dda6000000006f04b1a7
Object References
When we create a reference of an object variable by prefixing & to the name, any changes in the properties are automatically reflected in the reference variable ?
<?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;
?>
The output demonstrates that both variables share the same object and its properties ?
ID of obj1: 00000000163cf0b8000000003ad0ed93 ID of obj2: 00000000163cf0b8000000003ad0ed93 name: Amar
Key Differences
The main difference between object assignment ($obj2 = $obj1) and object reference ($obj2 = &$obj1) is that both create variables pointing to the same object, but references create true aliases where the variables themselves are linked.
Conclusion
PHP objects are always passed by reference through object identifiers. Understanding this behavior is crucial for proper object manipulation and avoiding unexpected side effects in your applications.
