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

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

新功能

其他回答

$var1 = 0;
$var2 = 0;

function test($testvar, &$var1 , &$var2)
{
  $var1 = 1;
  $var2 = 2;
  return;
}
test("", $var1, $var2);

// var1 = 1, var2 = 2 

这不是一个好方法,但我认为我们可以在一个函数中同时设置两个变量。

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

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.0以后,你可以使用新的语法(而不是list函数):

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

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

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

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

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

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

然后

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