Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by reference or return array in PHP? [closed]

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

like image 958
cgwebprojects Avatar asked Feb 08 '12 18:02

cgwebprojects


People also ask

Does PHP pass arrays by reference or value?

With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified.

Is passing by reference faster PHP?

In fact, in most scenarios passing by value is faster and less memory intensive than passing by reference. The Zend Engine, PHP's core, uses a copy-on-write optimization mechanism that does not create a copy of a variable until it is modified.

Is PHP object pass by reference?

In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value. It only contains an object identifier which allows using which the actual object is found.

Can you return an array in PHP?

Any type may be returned, including arrays and objects.


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

like image 99
FtDRbwLXw6 Avatar answered Oct 21 '22 11:10

FtDRbwLXw6