What is the good example of using 'func_get_arg' in PHP?

后端 未结 7 1177
梦谈多话
梦谈多话 2021-02-07 00:39

I just have found out that there is a function called func_get_arg in PHP which enables developer to use variant style of getting arguments. It seems to be very us

7条回答
  •  广开言路
    2021-02-07 01:06

    As of php5.6, there isn't a use case of func_get_arg anymore; which isn't to say that its functionality isn't needed anymore, but is replaced by the variadic function using the ... syntax:

    /**
     * @param array $arguments
     */
    public function poit(...$arguments)
    {
         foreach($arguments as $argument) {
             ...
         }
    }
    

    This is especially useful if there are methods that are overloaded at the end; one does need to filter out the first arguments anymore, as showcased by an example:

    Old style using func_get_arg:

    function foo($a, $b) {
        $c = array();
        if (func_num_args() > 2) {
            for($i = 0; $i < func_num_args()-2; $i++) {
                $c[] = func_get_arg($i+2);
            }
        }
        var_dump($a, $b, $c)
        // Do something
    }
    foo('a', 'b', 'c', 'd');
    

    Newer variadic style;

    function foo($a, $b, …$c) {
        var_dump($a, $b, $c);
        // Do something
    }
    foo('a', 'b', 'c', 'd');
    

    Both foo produce the same output, one is much simpler to write.

提交回复
热议问题