有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
当前回答
我想eligo已经解释得很清楚了。但如果你想返回两个值,把它们放到一个数组中并返回。
function test($testvar)
{
// do something
return array('var1'=>$var1,'var2'=>$var2);
//defining a key would be better some times
}
//访问返回值
$returned_values = test($testvar);
echo $returned_values['var1'];
echo $returned_values['var2'];
其他回答
在PHP 5.5中还有一个新概念:生成器,你可以从一个函数中产生多个值:
function hasMultipleValues() {
yield "value1";
yield "value2";
}
$values = hasMultipleValues();
foreach ($values as $val) {
// $val will first be "value1" then "value2"
}
有些人可能更喜欢返回多个值作为对象:
function test() {
$object = new stdClass();
$object->x = 'value 1';
$object->y = 'value 2';
return $object;
}
像这样叫它:
echo test()->x;
Or:
$test = test();
echo $test->y;
你总是只能返回一个变量,它可能是一个数组。但是你可以在函数内部修改全局变量。大多数时候,这不是很好的风格,但它是有效的。在类中,您通常从函数内部更改类变量而不返回它们。
没有办法返回两个变量。虽然,你可以传播一个数组并返回它;创建一个条件返回一个动态变量,等等。
例如,这个函数将返回$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
function foo(){
$you = 5;
$me = 10;
return $you;
return $me;
}
echo foo();
//output is just 5 alone so we cant get second one it only retuns first one so better go with array
function goo(){
$you = 5;
$me = 10;
return $you_and_me = array($you,$me);
}
var_dump(goo()); // var_dump result is array(2) { [0]=> int(5) [1]=> int(10) } i think thats fine enough
?>