开发者

func_get_args vs explicit arguments

I have been blissfully unaware of the php function fu开发者_如何学Gonc_get_args(), and now that I have discovered it I want to use it everywhere. Are there any limitations of using func_get_args as compared to explicit argument declaration in the function definition?


You shouldn't use func_get_args unless you actually need it.

If you define a function to take a specific number of arguments, PHP will raise an error if you don't supply enough arguments at call time.

If you take any number of arguments via func_get_args, it's up to you to specifically check that all the arguments you're expecting have been passed to your function.

Similarly, you lose the ability to use type hinting, you can't supply default values, and it becomes much harder to tell what arguments your function expects at a glance.

In short, you prevent PHP from helping you catch (potentially difficult to debug) logic errors.

function do_stuff(MyClass tmpValue, array $values, $optional = null) {
  // This is vastly better...
}

function do_stuff() {
  // ... than this
}

Even if you want to allow a variable number of arguments, you should explicitly specify as many arguments as you can:

/**
 * Add some numbers
 * Takes two or more numbers to add together
 */
function add_numbers($num_1, $num_2 /* ..., $num_N */) {
  $total = 0;
  for ($i = 0; $i < func_num_args(); ++$i)
    $total += func_get_arg($i);
  return $total;
}

add_numbers(1,2);   // OK!
add_numbers(1,2,3); // OK!
add_numbers(1)      // Error!


  • For starters I think it has a performance impact.
  • It makes your code much harder to read and understand.
  • No automatic error alert will make debugging a pain.


I think auto-completion is harder if not impossible to do for the IDE (it might use the phpdoc @param declaration though)

EDIT: you may use it when your have only one argument : a one-dimensional array, which keys do not matter. It then becomes very handy.


The only limitation I'm aware of is that stuff is harder to check at parse time. Note that this includes parsers for, say, automated documentation tools, since the functions have args that aren't right there in the function declaration

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜