'PHP - passing an array to a method does not reflect change, but object does

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?



Solution 1:[1]

You've sort of answered your own question. Simple answer is this is how PHP works, test2() is working with a copy of the array, unless you pass the array as a reference.

https://www.php.net/manual/en/language.references.pass.php

Alternatively you can return your array from test2(), and assign the returned value to your original array.

Edit: The reason this works with objects is that the object variable itself is just an identifier for the object, so technically the variable is also a copy when passed to another method, but the copy contains the same object identifier as your original variable. More on that here: https://www.php.net/manual/en/language.oop5.references.php

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1