开发者

Are multiple return values in PHP -- accepted / good practice?

in other languages it's common practice to have multiple return values. in Lua for example one could write:

local _, _, r1, r2 = string.find(...)

(the _ is in lua common practice for "throw-away" return values)

in PHP i would have to write something like:

list(, , $r1, $r2) = string_find(...);

While you can see the usage of multiple 开发者_Go百科return values in Lua really almost everywhere (in almost every program), i've seen this in PHP not very often -- besides of the while(list(...) = each(...)) { } case.

What is your opinion about multiple return values especially in PHP -- good practice or bad code?

thanks!


It's more common in PHP to return an array or an object, then work with that array or object directly, rather than assign all the values to separate variables.

function get_preferences() {
    return array('color' => 'red', 'size' => 'large', 'material' => 'cotton');
}

$prefs = get_preferences();

echo "We're sending you a " . $prefs['size'] . " shirt.";


To make that clear: "Return an array" is not the same as "return multiple values". Later one is simply not possible.

I sometimes return an array as a kind of "tupel", but there are very rare cases, where this is required. In most cases a function/method will return specific value.

For example you need a function, that splits a string at a given index. In this case I would return an array

function my_split ($string, $index) {
  return array(
    substr($string,0, $index),
    substr($string,$index)
  );
}
list($start, $end) = my_split("Hello World", 5);


There is nothing wrong in using multiple return values in PHP. At least if you are using it well. There are some situations when it can really help (for example returning a tuple can by funny doing this way).

Of course, you must be careful when documenting such methods. Also, if you are returning twenty values from a method, there is something very wrong with it. But, again, it's not related to PHP.

Now, why it's not used very often in PHP? In my opinion, because most people writing PHP programs are unaware of that.


I consider it to be okay, if used reasonably. Your second example, the one with while(list(...) = each(...)), is an example of where not to use it. Here it is just a slower variant of a foreach loop.

PS: Something I found recently: One can nest list()s :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜