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

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

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


当前回答

在PHP 5.5中还有一个新概念:生成器,你可以从一个函数中产生多个值:

function hasMultipleValues() {
    yield "value1";
    yield "value2";
}

$values = hasMultipleValues();
foreach ($values as $val) {
    // $val will first be "value1" then "value2"
}

其他回答

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

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

对于PHP 7.1.0以后,你可以使用新的语法(而不是list函数):

/**
* @return  array  [foo, bar]
*/
function getFooAndBar(): array {
    return ['foo', 'bar'];
}

[$foo, $bar] = getFooAndBar();

print 'Hello '. $foo . ' and ' . $bar;

如果你想返回2-3个变量,这对我来说是OK的,否则你应该使用一个具有所需属性的对象。

我也遇到了类似的问题——所以我试了一下,谷歌了一下(找到了这个帖子)。经过5分钟的尝试和错误,我发现你可以简单地使用 "AND"在一行中返回两个(可能更多——尚未测试)。

我的代码:

  function get_id(){
    global $b_id, $f_id;
    // stuff happens
    return $b_id AND $f_id;
  }
  //later in the code:
  get_id();
  var_dump($b_id);
  var_dump($f_id); // tested output by var_dump

它的工作原理。我得到了我期望得到/应该得到的两个值。我希望我能帮助到阅读这篇文章的人:)

从PHP 7.1开始,我们对列表进行了适当的解构。 因此你可以这样做:

$test = [1, 2, 3, 4];
[$a, $b, $c, $d] = $test;
echo($a);
> 1
echo($d);
> 4

在函数中是这样的:

function multiple_return() {
    return ['this', 'is', 'a', 'test'];
}

[$first, $second, $third, $fourth] = multiple_return();
echo($first);
> this
echo($fourth);
> test

解构是一个非常强大的工具。它也能够解构key=>值对:

["a" => $a, "b" => $b, "c" => $c] = ["a" => 1, "b" => 2, "c" => 3];

看看PHP 7.1的新特性页面:

新功能

根据定义,函数只返回一个值。

但是,正如您所假设的,该值可以是一个数组。

所以你当然可以这样做:

<?PHP
function myfunc($a,$b){
   return array('foo'=>$a,'bar'=>$b);
}
print_r(myfunc('baz','bork'));

也就是说,无论你想解决什么问题,花点时间想一想都是值得的。虽然返回一个复杂的结果值(如数组或对象)是完全有效的,但如果你的想法是“我想返回两个值”,那么你可能设计得很糟糕。如果你的问题没有更多的细节,这很难说,但停下来三思总是有益无害的。