Multiple returns from a function

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

    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 :)

    0 讨论(0)
  • 2020-11-22 06:35

    Or you can pass by reference:

    function byRef($x, &$a, &$b)
    {
        $a = 10 * $x;
        $b = 100 * $x;
    }
    
    $a = 0;
    $b = 0;
    
    byRef(10, $a, $b);
    
    echo $a . "\n";
    echo $b;
    

    This would output

    100
    1000
    
    0 讨论(0)
  • 2020-11-22 06:36

    In PHP 5.5 there is also a new concept: generators, where you can yield multiple values from a function:

    function hasMultipleValues() {
        yield "value1";
        yield "value2";
    }
    
    $values = hasMultipleValues();
    foreach ($values as $val) {
        // $val will first be "value1" then "value2"
    }
    
    0 讨论(0)
  • 2020-11-22 06:37

    You can get the values of two or more variables by setting them by reference:

    function t(&$a, &$b) {
        $a = 1;
        $b = 2;
    }
    
    
    t($a, $b);
    
    echo $a . '  ' . $b;
    

    Output:

    1 2
    
    0 讨论(0)
  • 2020-11-22 06:39

    Does PHP still use "out parameters"? If so, you can use the syntax to modify one or more of the parameters going in to your function then. You would then be free to use the modified variable after your function returns.

    0 讨论(0)
  • 2020-11-22 06:40

    Best Practice is to put your returned variables into array and then use list() to assign array values to variables.

    <?php
    
    function add_subt($val1, $val2) {
        $add = $val1 + $val2;
        $subt = $val1 - $val2;
    
        return array($add, $subt);
    }
    
    list($add_result, $subt_result) = add_subt(20, 7);
    echo "Add: " . $add_result . '<br />';
    echo "Subtract: " . $subt_result . '<br />';
    
    ?>
    
    0 讨论(0)
提交回复
热议问题