有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
当前回答
我想我应该对上面的一些回复进行扩展....
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。 希望这能有所帮助!
其他回答
没有办法返回两个变量。虽然,你可以传播一个数组并返回它;创建一个条件返回一个动态变量,等等。
例如,这个函数将返回$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
是的,你可以使用对象:-)
但最简单的方法是返回一个数组:
return array('value1', 'value2', 'value3', '...');
我也遇到了类似的问题——所以我试了一下,谷歌了一下(找到了这个帖子)。经过5分钟的尝试和错误,我发现你可以简单地使用 "AND"在一行中返回两个(可能更多——尚未测试)。
我的代码:
function get_id(){
global $b_id, $f_id;
// stuff happens
return $b_id AND $f_id;
}
//later in the code:
get_id();
var_dump($b_id);
var_dump($f_id); // tested output by var_dump
它的工作原理。我得到了我期望得到/应该得到的两个值。我希望我能帮助到阅读这篇文章的人:)
有些人可能更喜欢返回多个值作为对象:
function test() {
$object = new stdClass();
$object->x = 'value 1';
$object->y = 'value 2';
return $object;
}
像这样叫它:
echo test()->x;
Or:
$test = test();
echo $test->y;
答案是否定的。当解析器到达第一个return语句时,它将把控制转回调用函数—您的第二个return语句将永远不会执行。