Multiple returns from a function

后端 未结 30 2279
盖世英雄少女心
盖世英雄少女心 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:49

    This is the easiest way to do it:

    public function selectAllUsersByRole($userRole, $selector) {
    
        $this->userRole = $userLevel;
        $this->selector = $selector;
    
        $sql = "SELECT * FROM users WHERE role <= ? AND del_stat = 0";
        $stm = $this->connect()->prepare($sql); // Connect function in Dbh connect to database file
        $stm->execute([$this->userRole]); // This is PHP 7. Use array($this->userRole) for PHP 5
    
        $usersIdArray = array();
        $usersFNameArray = array();
        $usersLNameArray = array();
    
        if($stm->rowCount()) {
            while($row = $stm->fetch()) {
    
                array_push($usersIdArray,    $row['id']);
                array_push($usersFNameArray, $row['f_name']);
                array_push($usersLNameArray, $row['l_name']);
    
                // You can return only $row['id'] or f_name or ...
                // I used the array because it's most used.
            }
        }
        if($this->selector == 1) {
            return $usersIdArray;
        }elseif($this->selector == 2) {
            return $usersFNameArray;
        }elseif($this->selector == 3) {
            return $usersLNameArray;
        }
    
    }
    

    How can we call this function?

    $idData = $selectAllUsers->selectAllUsersByLevel($userRole, 0);
    print_r($idData);
    $idFName = $selectAllUsers->selectAllUsersByLevel($userRole, 1);
    print_r($idFname);
    

    That's it. Very easy.

提交回复
热议问题