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 に答える