0

假设:在 PHP 中使用参数(或不使用)。

Class myclass {
  function noArgument() {
    echo "no arguments<br>";
  }
  function oneArgument($one) {
    echo "the only argument is ".$one."<br>";
  }
  function twoArgument($one,$two) {
    echo "the first argument is ".$one." the second is ".$two."<br>";
  }
}

现在,我向您展示我对上一课的测试。

$TestMyClass = new myclass();

echo "<br>Omiting arguments<br>";
$TestMyClass->twoArgument("*Lack one*");
$TestMyClass->oneArgument();

echo "<br>Excess arguments<br>";
$TestMyClass->noArgument("*With Argument*");
$TestMyClass->oneArgument("*First Argument*", "*Second Argument*");

echo "<br>End Test<br>";

结果

Omiting arguments

Warning: Missing argument 2 for myclass::twoArgument(), called in C:\...\test.php on line 4 and defined in C:\...\test.php on line 18

Notice: Undefined variable: two in C:\...\test.php on line 19
the first argument is *Lack one* the second is

Warning: Missing argument 1 for myclass::oneArgument(), called in C:\...\test.php on line 5 and defined in C:\...\test.php on line 15

Notice: Undefined variable: one in C:\...\test.php on line 16
the only argument is

Excess arguments
no arguments
the only argument is *First Argument*

End Test

我需要对多余的论点进行类似的处理!我也需要在使用不必要的参数时引发错误(或限制参数的数量)!

4

2 回答 2

0

You can use the function func_num_args() to check how many arguments are being passed and throw an Exception if there are too many.

于 2014-02-10T03:10:39.717 回答
0

There is a function called func_num_args() that is used to show how many arguments a function received.

This short sample should give you an idea of how you can implement it:

function testfunc($arg1, $arg2)
{
    if (func_num_args() > 2)
    { 
        echo "Error!";
    }
    else
    {
        echo "Arg1 => $arg1, Arg2 => $arg2";
    }
}

testfunc(1,2,3,4);

Outputs:

Error!

A call of

testfunc(1,2)

Outputs:

Arg1 => 1, Arg2 => 2
于 2014-02-10T03:13:48.280 回答