Recipe 6.7. Returning More Than One Value


6.7.1. Problem

You want to return more than one value from a function.

6.7.2. Solution

Return an array and use list( ) to separate elements:

function averages($stats) {     ...     return array($median, $mean, $mode); } list($median, $mean, $mode) = averages($stats);

6.7.3. Discussion

From a performance perspective, this isn't a great idea. There is a bit of overhead because PHP is forced to first create an array and then dispose of it. That's what is happening in this example:

function time_parts($time) {     return explode(':', $time); } list($hour, $minute, $second) = time_parts('12:34:56');

You pass in a time string as you might see on a digital clock and call explode( ) to break it apart as array elements. When time_parts( ) returns, use list( ) to take each element and store it in a scalar variable. Although this is a little inefficient, the other possible solutions are worse because they can lead to confusing code.

One alternative is to pass the values in by reference. However, this is somewhat clumsy and can be nonintuitive since it doesn't always make logical sense to pass the necessary variables into the function. For instance:

function time_parts($time, &$hour, &$minute, &$second) {     list($hour, $minute, $second) = explode(':', $time); } time_parts('12:34:56', $hour, $minute, $second);

Without knowledge of the function prototype, there's no way to look at this and know $hour, $minute, and $second are, in essence, the return values of time_parts( ).

You can also use global variables, but this clutters the global namespace and also makes it difficult to easily see which variables are being silently modified in the function. For example:

function time_parts($time) {     global $hour, $minute, $second;     list($hour, $minute, $second) = explode(':', $time); } time_parts('12:34:56');

Again, here it's clear because the function is directly above the call, but if the function is in a different file or written by another person, it'd be more mysterious and thus open to creating a subtle bug.

Our advice is that if you modify a value inside a function, return that value and assign it to a variable unless you have a very good reason not to, such as significant performance issues. It's cleaner and easier to understand and maintain.

6.7.4. See Also

Recipe 6.3 on passing values by reference and Recipe 6.11 for information on variable scoping.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net