Multiple returns from a function

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

提交回复
热议问题