一尘不染

一个函数的多次返回

php

是否有可能具有两个返回的函数,如下所示:

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

如果是这样,我如何才能分别获得每份退货?


阅读 431

收藏
2020-05-26

共1个答案

一尘不染

无法返回两个变量。虽然,您 可以 传播一个数组并返回它;创建条件以返回动态变量,等等。

例如,此函数将返回 $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

如果您都想要它们,可以稍微修改一下功能

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
2020-05-26