有可能有一个函数有两个返回值,像这样:

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

如果是这样,我怎样才能分别得到每一个回报?


当前回答

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

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

其他回答

在数组中添加所有变量,然后最终返回数组。

function test($testvar)
{
  // do something
  return array("var1" => $var1, "var2" => @var2);
}

然后

$myTest = test($myTestVar);
//$myTest["var1"] and $myTest["var2"] will be usable

有些人可能更喜欢返回多个值作为对象:

function test() {
    $object = new stdClass();

    $object->x = 'value 1';
    $object->y = 'value 2';

    return $object;
}

像这样叫它:

echo test()->x;

Or:

$test = test();
echo $test->y;

我知道我迟到了,但是有一个很好的简单的解决方法。 使用解构可以一次返回多个值。

function test()
{
    return [ 'model' => 'someValue' , 'data' => 'someothervalue'];
}

现在你可以用这个

$result = test();
extract($result);

Extract为数组中的每个成员创建一个变量,以该成员命名。因此,您现在可以访问$model和$data

是的,你可以使用对象:-)

但最简单的方法是返回一个数组:

return array('value1', 'value2', 'value3', '...');
$var1 = 0;
$var2 = 0;

function test($testvar, &$var1 , &$var2)
{
  $var1 = 1;
  $var2 = 2;
  return;
}
test("", $var1, $var2);

// var1 = 1, var2 = 2 

这不是一个好方法,但我认为我们可以在一个函数中同时设置两个变量。