Multiple returns from a function

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

    Since PHP 7.1 we have proper destructuring for lists. Thereby you can do things like this:

    $test = [1, 2, 3, 4];
    [$a, $b, $c, $d] = $test;
    echo($a);
    > 1
    echo($d);
    > 4
    

    In a function this would look like this:

    function multiple_return() {
        return ['this', 'is', 'a', 'test'];
    }
    
    [$first, $second, $third, $fourth] = multiple_return();
    echo($first);
    > this
    echo($fourth);
    > test
    

    Destructuring is a very powerful tool. It's capable of destructuring key=>value pairs as well:

    ["a" => $a, "b" => $b, "c" => $c] = ["a" => 1, "b" => 2, "c" => 3];
    

    Take a look at the new feature page for PHP 7.1:

    New features

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

    In your example, the second return will never happen - the first return is the last thing PHP will run. If you need to return multiple values, return an array:

    function test($testvar) {
    
        return array($var1, $var2);
    }
    
    $result = test($testvar);
    echo $result[0]; // $var1
    echo $result[1]; // $var2
    
    0 讨论(0)
  • 2020-11-22 06:56

    Some might prefer returning multiple values as object:

    function test() {
        $object = new stdClass();
    
        $object->x = 'value 1';
        $object->y = 'value 2';
    
        return $object;
    }
    

    And call it like this:

    echo test()->x;
    

    Or:

    $test = test();
    echo $test->y;
    
    0 讨论(0)
  • 2020-11-22 06:56

    The answer is no. When the parser reaches the first return statement, it will direct control back to the calling function - your second return statement will never be executed.

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

    I know that I am pretty late, but there is a nice and simple solution for this problem.
    It's possible to return multiple values at once using destructuring.

    function test()
    {
        return [ 'model' => 'someValue' , 'data' => 'someothervalue'];
    }
    

    Now you can use this

    $result = test();
    extract($result);
    

    extract creates a variable for each member in the array, named after that member. You can therefore now access $model and $data

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

    For PHP 7.1.0 onwards, you can use the new syntax (instead of the list function):

    /**
    * @return  array  [foo, bar]
    */
    function getFooAndBar(): array {
        return ['foo', 'bar'];
    }
    
    [$foo, $bar] = getFooAndBar();
    
    print 'Hello '. $foo . ' and ' . $bar;
    
    

    It's OK for me if you want to return 2-3 variables, otherwise you should use an object with the desired properties.

    0 讨论(0)
提交回复
热议问题