0

是否可以计算 PHP 函数中缺少的参数?我想做这个:

// I have this
function foo($param1, $param2, $param3) {
    // I need some sort of argument counter
}

foo("hello", "world");

当我使用上面的 foo 函数时,我想要一种方法来找出并非所有参数都被使用。

通过计算所有参数并与 get_defined_vars() 进行比较,或者使用一个函数来计算缺失参数的数量。

编辑:如果打开 error_reporting 时缺少某些参数,我需要停止运行的方法。

if(!foo($param)) { echo "Couldn't Foo!"; }
4

5 回答 5

3

采用func_num_args()

于 2012-05-04T10:41:09.777 回答
2

如果您想以超动态方式执行此操作,请使用反射来获取预期的参数计数并将该数字与 func_num_args() 返回的值进行比较:

function foo($p1 = null, $p2 = null, $p3 = null) {
    $refl = new ReflectionFunction(__FUNCTION__);

    $actualNumArgs = func_num_args();
    $expectedNumArgs = $refl->getNumberOfParameters();

    $numMissingArgs = $expectedNumArgs - $actualNumArgs;

    // ...
于 2012-05-04T10:46:29.990 回答
1

调用参数不足的函数将引发错误。如果您需要允许调用具有较少参数的函数,则需要在函数声明中使用默认值定义它们并测试默认值以查看哪些已被省略。

像这样的东西(再次改进):

function foo () {

  // Names of possible function arguments
  // This replaces the list of arguments in the function definition parenthesis
  $argList = array('param1', 'param2', 'param3');

  // Actual function arguments
  $args = func_get_args();

  // The number of omitted arguments
  $omittedArgs = 0;

  // Loop the list of expected arguments
  for ($i = 0; isset($argList[$i]); $i++) {
    if (!isset($args[$i])) { // The argument was omitted - this also allows you to skip arguments with NULL since NULL is not counted as set
      // increment the counter and create a NULL variable in the local scope
      $omittedArgs++;
      ${$argList[$i]} = NULL;
    } else {
      // The argument was passed, create a variable in the local scope
      ${$argList[$i]} = $args[$i];
    }
  }

  // Function code goes here
  var_dump($omittedArgs);

}

这对于可能维护代码的其他人来说有点违反直觉 - 参数列表现在维护为字符串数组而不是函数参数列表,但除此之外它是完全动态的并且可以实现您想要的。

于 2012-05-04T11:24:38.223 回答
0

根据您的需要,最简单的解决方案可能是默认参数:

function foo($param1 = null, $param2 = null, $param3 = null) {
  if ($param3 !== null) {
    // 3 params are specified
  } else if ($param2 !== null) {
    // 2 params are specified
  } else if ($param1 !== null) {
    // 1 param is specified
  } else {
    // no param is specified
  }
}
于 2012-05-04T10:42:07.907 回答
0

您可以使用内置的 php 函数:

参数数组:http: //php.net/manual/en/function.func-get-args.php

参数数量:http: //php.net/manual/en/function.func-num-args.php

从数组 http://php.net/manual/en/function.func-get-arg.php获取参数

于 2012-05-04T10:42:31.257 回答