How does PHP handle object references in functions, especially when modifying nested objects within arrays?
When passing objects to functions in PHP, they are passed by reference by default, meaning any modifications made to the object inside the function will affect the original object outside of the function. However, when dealing with nested objects within arrays, PHP will create a copy of the object instead of passing it by reference. To work around this, you can use the `&` symbol when passing nested objects within arrays to ensure they are passed by reference.
<?php
class NestedObject {
public $value;
}
function modifyNestedObject(&$nestedObject) {
$nestedObject->value = 'Modified';
}
$nestedObject = new NestedObject();
$nestedObject->value = 'Original';
$array = ['nestedObject' => &$nestedObject];
modifyNestedObject($array['nestedObject']);
echo $nestedObject->value; // Output: Modified