When passing an array to a method, we have to return it in order to reflect the changes inside the passed array, as values are only copied to methods, and not passed-by-reference. We can only achieve this by adding & to the method signature, but I feel its bad practice to do so (and the code gets smelly IMO).
However, for Objects its a bit different. Any object passed to a method will be set even if the return type of the method is void.
Lets say we have this method:
public function test1()
{
$array = ['test' => 1, 'foo' => 'bar'];
$this->test2($array);
var_dump($array);
}
public function test2($array)
{
foreach(range(1,10) as $step) {
$array['steps'][$step] = true;
}
}
The result of this will be:
array(2) {
["test"]=>
int(1)
["foo"]=>
string(3) "bar"
}
How can I pass an array as reference without using & and without having to write something like this: $data = $this->test2($data);, or is it simply impossible due to PHPs pointer table?
&in the first place?&is doing under the hood.