0

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?

4
  • 1
    Why you don't wish to use & in the first place? Commented May 23, 2022 at 10:46
  • @nice_dev because it mostly makes code harder to understand for other Developers, generally speaking. Return an array is crystal clear, but having multiple arrays being modified in one method feels very wrong. Commented May 23, 2022 at 10:57
  • It totally depends on the use-case at hand and developers are expected to know or understand what & is doing under the hood. Commented May 23, 2022 at 11:07
  • When you need to make multiple modifications to related datas, you're at a point where you may want to consider turning your dataset into a class/object with said datas as array-type class properties, and further, have separate methods for each modification to separate your concerns. Commented May 23, 2022 at 12:22

1 Answer 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.