有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
当前回答
PHP 7.1更新
返回一个数组。
function test($testvar)
{
// Do something
return [$var1, $var2];
}
然后像下面这样使用:
[$value1, $value2] = test($testvar);
其他回答
从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的新特性页面:
新功能
没有办法返回两个变量。虽然,你可以传播一个数组并返回它;创建一个条件返回一个动态变量,等等。
例如,这个函数将返回$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
你可以通过引用来设置两个或多个变量的值:
function t(&$a, &$b) {
$a = 1;
$b = 2;
}
t($a, $b);
echo $a . ' ' . $b;
输出:
1 2
我已经实现了这样的多返回值PHP函数。善待你的代码。谢谢你!
<?php
function multi_retun($aa)
{
return array(1,3,$aa);
}
list($one,$two,$three)=multi_retun(55);
echo $one;
echo $two;
echo $three;
?>
PHP 7.1更新
返回一个数组。
function test($testvar)
{
// Do something
return [$var1, $var2];
}
然后像下面这样使用:
[$value1, $value2] = test($testvar);