Multiple returns from a function

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

提交回复
热议问题