有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
当前回答
它不可能有两个返回语句。然而,它不会抛出错误,但当函数被调用时,你只会收到第一个返回语句值。 我们可以使用return of array来获取多个返回值。例如:
function test($testvar)
{
// do something
//just assigning a string for example, we can assign any operation result
$var1 = "result1";
$var2 = "result2";
return array('value1' => $var1, 'value2' => $var2);
}
其他回答
PHP 7.1更新
返回一个数组。
function test($testvar)
{
// Do something
return [$var1, $var2];
}
然后像下面这样使用:
[$value1, $value2] = test($testvar);
<?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
?>
我已经实现了这样的多返回值PHP函数。善待你的代码。谢谢你!
<?php
function multi_retun($aa)
{
return array(1,3,$aa);
}
list($one,$two,$three)=multi_retun(55);
echo $one;
echo $two;
echo $three;
?>
我想我应该对上面的一些回复进行扩展....
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 test($testvar) {
return array($var1, $var2);
}
$result = test($testvar);
echo $result[0]; // $var1
echo $result[1]; // $var2