Home » Php » Pass by reference or return array in PHP?

Pass by reference or return array in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

All of my functions that have multiple parameters and that need to return more than one of those values I return an array like so…

function eg($a, $b) {
    $a += 5;
    $b += 10;
    return array('a' => $a, 'b' => $b);
}
$no = eg(0, 5);
echo $no['a']; // 5
echo $no['b']; // 10

Is this considered bad practice compared to passing by reference ie;

function eg(&$a, &$b) {
    $a += 5;
    $b += 10;
}  
eg(0, 5);
echo $a; // 5
echo $b; // 10

Does this really matter? When would I want to use one over the other when using the examples above? Is there any difference in performance?

Thanks

How to&Answers:

As most of the comments have pointed out, the first method (returning an array) is cleaner and easier to understand, so by that metric, it’s “better”.

Depending on your use-case, though, it may even be better not to try and return multiple values at all. Consider:

public function getDimensions() {
    return array(
        'width' => $this->_width,
        'height' => $this->_height
    );
}

$dim = $canvas->getDimensions();
echo $dim['width'], ' x ', $dim['height'];

Compared to:

public function getWidth() {
    return $this->_width;
}

public function getHeight() {
    return $this->_height;
}

echo $canvas->getWidth(), ' x ', $canvas->getHeight();

This is a contrived example, obviously, but imagine that your methods do something expensive instead of frivolous. Now imagine that you only need the first of the set of values, but since your method calculates all of them for every invocation, you have to wastefully calculate everything and discard what you didn’t need.