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

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

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


当前回答

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

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

其他回答

允许多次返回的语言通常只是将多个值转换为一个数据结构。

例如,在Python中,您可以返回多个值。但是,它们实际上只是作为一个元组返回。

你可以在PHP中返回多个值只需创建一个简单数组并返回。

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

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

return array('value1', 'value2', 'value3', '...');

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

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

现在你可以用这个

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

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

我想eligo已经解释得很清楚了。但如果你想返回两个值,把它们放到一个数组中并返回。

function test($testvar)
{
  // do something

  return array('var1'=>$var1,'var2'=>$var2);
//defining a key would be better some times   
}

//访问返回值

$returned_values = test($testvar);

echo $returned_values['var1'];
echo $returned_values['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