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

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;
    ?>

其他回答

我想我应该对上面的一些回复进行扩展....

class nameCheck{

public $name;

public function __construct(){
    $this->name = $name;
}

function firstName(){
            // If a name has been entered..
    if(!empty($this->name)){
        $name = $this->name;
        $errflag = false;
                    // Return a array with both the name and errflag
        return array($name, $errflag);
            // If its empty..
    }else if(empty($this->name)){
        $errmsg = 'Please enter a name.';
        $errflag = true;
                    // Return both the Error message and Flag
        return array($errmsg, $errflag);
    }
}

}


if($_POST['submit']){

$a = new nameCheck;
$a->name = $_POST['name'];
//  Assign a list of variables from the firstName function
list($name, $err) = $a->firstName();

// Display the values..
echo 'Name: ' . $name;
echo 'Errflag: ' . $err;
}

?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" >
<input name="name"  />
<input type="submit" name="submit" value="submit" />
</form>

这将为您提供一个输入字段和提交按钮,一旦提交,如果名称输入字段为空,它将返回错误标志和一条消息。如果name字段有值,它将返回值/name,如果false =无错误,则返回错误标志0。 希望这能有所帮助!

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

新功能

我也遇到了类似的问题——所以我试了一下,谷歌了一下(找到了这个帖子)。经过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

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

是也不是。你不能返回一个以上的变量/对象,但如你所建议的,你可以把它们放入一个数组并返回。

数组的嵌套是没有限制的,所以您可以将它们打包并返回。

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

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

然后

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