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

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

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


当前回答

PHP中的函数只能返回一个变量。你可以使用全局作用域的变量,你可以返回数组,或者你可以通过引用传递变量给函数,然后改变值。但所有这些都会降低代码的可读性。 我建议你研究一下课程。

其他回答

在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的,否则你应该使用一个具有所需属性的对象。

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

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

所以你当然可以这样做:

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

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

从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的新特性页面:

新功能