有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
当前回答
$var1 = 0;
$var2 = 0;
function test($testvar, &$var1 , &$var2)
{
$var1 = 1;
$var2 = 2;
return;
}
test("", $var1, $var2);
// var1 = 1, var2 = 2
这不是一个好方法,但我认为我们可以在一个函数中同时设置两个变量。
其他回答
我想我应该对上面的一些回复进行扩展....
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 t($a)
{
global $add, $noadd;
$add=$a+$a;
$noadd=$a;
}
$a=1;
t($a);
echo $noadd." ".$add;
?>
这将回显12
PHP中的函数只能返回一个变量。你可以使用全局作用域的变量,你可以返回数组,或者你可以通过引用传递变量给函数,然后改变值。但所有这些都会降低代码的可读性。 我建议你研究一下课程。
对于PHP 7.1.0以后,你可以使用新的语法(而不是list函数):
/**
* @return array [foo, bar]
*/
function getFooAndBar(): array {
return ['foo', 'bar'];
}
[$foo, $bar] = getFooAndBar();
print 'Hello '. $foo . ' and ' . $bar;
如果你想返回2-3个变量,这对我来说是OK的,否则你应该使用一个具有所需属性的对象。
没有办法返回两个变量。虽然,你可以传播一个数组并返回它;创建一个条件返回一个动态变量,等等。
例如,这个函数将返回$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