func_get_args vs显式参数

myt*_*oth 13 php

我一直没有意识到PHP的功能func_get_args(),现在我已经发现它我想在任何地方使用它.func_get_args与函数定义中的显式参数声明相比,使用是否有任何限制?

mea*_*gar 12

func_get_args除非您确实需要,否则不应使用它.

如果定义一个函数来获取特定数量的参数,如果在调用时没有提供足够的参数,PHP将引发错误.

如果您通过任意数量的参数func_get_args,则由您专门检查您期望的所有参数是否已传递给您的函数.

类似地,您失去了使用类型提示的能力,您无法提供默认值,并且更难以一目了然地告诉您的函数所期望的参数.

简而言之,您可以防止PHP帮助您捕获(可能很难调试)逻辑错误.

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

function do_stuff() {
  // ... than this
}
Run Code Online (Sandbox Code Playgroud)

即使您想允许可变数量的参数,也应该尽可能明确地指定尽可能多的参数:

/**
 * 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!
Run Code Online (Sandbox Code Playgroud)