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

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

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


当前回答

从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 5.5中还有一个新概念:生成器,你可以从一个函数中产生多个值:

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

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

上面的绿色勾号给出的答案实际上是不正确的。如果返回一个数组,则可以在PHP中返回多个值。请看下面的示例代码:

<?php

function small_numbers()
{
    return array (0, 1, 2);
}

list ($zero, $one, $two) = small_numbers();

这段代码实际上是从PHP网站上的以下页面复制的:http://php.net/manual/en/functions.returning-values.php 我自己也使用过很多次相同类型的代码,所以可以确认它是好的,它可以工作。

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

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

然后

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

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

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
function myfunc($a,$b){
   return array('foo'=>$a,'bar'=>$b);
}
print_r(myfunc('baz','bork'));

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