Why do PHP objects appear to pass by reference by default, and how does object cloning (clone $obj) work?
❓ Interview Prompt: Explain PHP Object Identifiers (handles), object copying behavior, and cloning objects with the clone keyword and __clone() magic method.
In PHP 5+, object variables do not store the actual object data directly; they store an Object Identifier handle pointing to the memory location of the object instance.
Passing Objects to Functions:
When you pass an object variable to a function, PHP passes a copy of the handle. Because both handles point to the exact same underlying object, modifying object properties inside the function mutates the original object!
Cloning Objects ('clone $obj'):
To create a true, independent copy of an object, use the 'clone' keyword. You can customize cloning logic using the '__clone()' magic method to perform deep copies of nested objects.
Code Implementation Example
<?php
class User {
public string $name = "Alice";
}
$u1 = new User();
$u2 = $u1; // Both handles point to SAME object!
$u2->name = "Bob";
echo $u1->name; // Outputs: Bob
// True independent copy using clone
$u3 = clone $u1;
$u3->name = "Charlie";
echo $u1->name; // Outputs: Bob (unmodified!)Object variables hold handle pointers to instances. Use the clone keyword to create an independent copy of an object instance.