Multiple returns from a function

后端 未结 30 2820
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:12

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

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}
<
30条回答
  •  暖寄归人
    2020-11-22 06:52

    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;
    }
    
    ?>
    

    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!

提交回复
热议问题