一个函数的多次返回 [英] Multiple returns from a function
本文介绍了一个函数的多次返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可能有一个具有两个返回的函数,如下所示:
Is it possible to have a function with two returns like this:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我如何才能分别获得每份退货?
If so, how would I be able to get each return separately?
推荐答案
无法返回2个变量.虽然,您 可以 传播数组并返回它;创建条件以返回动态变量等.
There is no way of returning 2 variables. Although, you can propagate an array and return it; create a conditional to return a dynamic variable, etc.
例如,此函数将返回$var2
function wtf($blahblah = true) {
$var1 = "ONe";
$var2 = "tWo";
if($blahblah === true) {
return $var2;
}
return $var1;
}
在申请中:
echo wtf();
//would echo: tWo
echo wtf("not true, this is false");
//would echo: ONe
如果您俩都想要,则可以对其进行一些修改
If you wanted them both, you could modify the function a bit
function wtf($blahblah = true) {
$var1 = "ONe";
$var2 = "tWo";
if($blahblah === true) {
return $var2;
}
if($blahblah == "both") {
return array($var1, $var2);
}
return $var1;
}
echo wtf("both")[0]
//would echo: ONe
echo wtf("both")[1]
//would echo: tWo
list($first, $second) = wtf("both")
// value of $first would be $var1, value of $second would be $var2
这篇关于一个函数的多次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文