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

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

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


当前回答

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

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

现在你可以用这个

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

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

其他回答

在你的例子中,第二次返回永远不会发生——第一次返回是PHP运行的最后一件事。如果你需要返回多个值,返回一个数组:

function test($testvar) {

    return array($var1, $var2);
}

$result = test($testvar);
echo $result[0]; // $var1
echo $result[1]; // $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()
{
    return [ 'model' => 'someValue' , 'data' => 'someothervalue'];
}

现在你可以用这个

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

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

<?php
function foo(){
  $you = 5;
  $me = 10;
  return $you;
  return $me;
}

echo foo();
//output is just 5 alone so we cant get second one it only retuns first one so better go with array


function goo(){
  $you = 5;
  $me = 10;
  return $you_and_me =  array($you,$me);
}

var_dump(goo()); // var_dump result is array(2) { [0]=> int(5) [1]=> int(10) } i think thats fine enough

?>

我已经实现了这样的多返回值PHP函数。善待你的代码。谢谢你!

 <?php
    function multi_retun($aa)
    {
        return array(1,3,$aa);
    }
    list($one,$two,$three)=multi_retun(55);
    echo $one;
    echo $two;
    echo $three;
    ?>