Skip a link or return an array in PHP?

All my functions that have several parameters, and which should return more than one of these values, return an array like ...

 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 a bad practice compared to passing by reference, i.e.

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

Does it really matter? When will I use one above the other when using the examples above? Is there a difference in performance?

thanks

+6
source share
1 answer

As noted in most comments, the first method (returning an array) is cleaner and more understandable, so it’s β€œbetter” by this metric.

Depending on your use case, it might even be better not to try to 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 with:

 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, not frivolous. Now imagine that you only need the first set of values, but since your method computes all of them for each call, you should wastefully compute everything and discard what you don't need.

+6
source

Source: https://habr.com/ru/post/907974/


All Articles