PHP get all arguments as array?

前端 未结 3 1747
悲&欢浪女
悲&欢浪女 2020-12-01 11:47

Hey, I was working with a PHP function that takes multiple arguments and formats them. Currently, I\'m working with something like this:

function foo($a1 =          


        
相关标签:
3条回答
  • 2020-12-01 12:25

    func_get_args returns an array with all arguments of the current function.

    0 讨论(0)
  • 2020-12-01 12:36

    If you use PHP 5.6+, you can now do this:

    <?php
    function sum(...$numbers) {
        $acc = 0;
        foreach ($numbers as $n) {
            $acc += $n;
        }
        return $acc;
    }
    
    echo sum(1, 2, 3, 4);
    ?>
    

    source: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

    0 讨论(0)
  • 2020-12-01 12:38

    Or as of PHP 7.1 you are now able to use a type hint called iterable

    function f(iterable $args) {
        foreach ($args as $arg) {
            // awesome stuff
        }
    }
    

    Also, it can be used instead of Traversable when you iterate using an interface. As well as it can be used as a generator that yields the parameters.

    Documentation

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