Multiple returns from function

2018-12-31 18:26发布

Is it possible to have a function with 2 returns like this:

function test($testvar)
{
  // do something

  return $var1;
  return $var2;
}

If so, how would I be able to get each return separately?

标签: php
28条回答
路过你的时光
2楼-- · 2018-12-31 19:25

I had a similar problem - so I tried around and googled a bit (finding this thread). After 5 minutes of try and error I found out that you can simply use "AND" to return two (maybe more - not tested yet) in one line of return.

My code:

  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

it works. I got both the values I expected to get/should get. I hope I could help anybody reading this thread :)

查看更多
梦该遗忘
3楼-- · 2018-12-31 19:26

You can return multiple arrays and scalars from a function

function x()
{
    $a=array("a","b","c");
    $b=array("e","f");
    return array('x',$a,$b);
}

list ($m,$n,$o)=x();

echo $m."\n";
print_r($n);
print_r($o);
查看更多
美炸的是我
4楼-- · 2018-12-31 19:26

Thought I would expand on a few of the responses from above....

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>

This will give you a input field and a submit button once submitted, if the name input field is empty it will return the error flag and a message. If the name field has a value it will return the value/name and a error flag of 0 for false = no errors. Hope this helps!

查看更多
有味是清欢
5楼-- · 2018-12-31 19:26

Languages which allow multiple returns usually just convert the multiple values into a data structure.

For example, in python you can return multiple values, however they're actually just being returned as 1 tuple.

So you can return multiple values in PHP by just creating a simple array and returning that.

查看更多
登录 后发表回答