扫码关注官方订阅号
是否可以有一个具有两个返回值的函数,如下所示:
function test($testvar) { // Do something return $var1; return $var2; }
如果是这样,我如何才能分别获得每笔回报?
无法返回 2 个变量。不过,您可以传播一个数组并返回它;创建条件以返回动态变量等。
例如,此函数将返回 $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
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
无法返回 2 个变量。不过,您可以传播一个数组并返回它;创建条件以返回动态变量等。
例如,此函数将返回
$var2function 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