Multiple returns from a function

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

    There is no way of returning 2 variables. Although, you can propagate an array and return it; create a conditional to return a dynamic variable, etc.

    For instance, this function would return $var2

    function wtf($blahblah = true) {
        $var1 = "ONe";
        $var2 = "tWo";
    
        if($blahblah === true) {
          return $var2;
        }
        return $var1;
    }
    

    In application:

    echo wtf();
    //would echo: tWo
    echo wtf("not true, this is false");
    //would echo: ONe
    

    If you wanted them both, you could modify the function a bit

    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
    

提交回复
热议问题