PHP function arguments by reference
A short article on PHP function arguments
Everyone knows since PHP5, objects are passed by reference to the functions and methods. That mean modifying an object in a function modifies directly the data pointed by the variables.
<?phpclass A { public $data; }function modifyA(A $instance) { $instance->data = 1000; }$a = new A(); $a->data = 0; modifyA($a); echo $a->data; // 1000
As the local variable $instance and $a point internally to the same data structure in memory, modifying $instance is the same as modifying $a. Adding a & front of the $instance declaration in function signature forces PHP to pass data as reference and should have exactly the same results.
Have now a look at the following code, you will understand it is not the case:
<?phpclass A { public $data; }function modifyA(A $instance) { if ($instance->data === 0) { $instance = new A(); }$instance->data = 1000; }$a = new A(); $a->data = 0; modifyA($a); echo $a->data; // 0 modifyA(&$a); echo $a->data; // 1000
Hope that will save you some time.