【问题标题】:Throwing Error/Exception when an unnecessary Argument is sent in PHP在 PHP 中发送不必要的参数时抛出错误/异常
【发布时间】:2014-02-10 02:57:49
【问题描述】:

假设: 在 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

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

【问题讨论】:

    标签: php arguments limiting


    【解决方案1】:

    您可以使用函数func_num_args() 来检查传递了多少参数,如果太多则抛出Exception

    【讨论】:

      【解决方案2】:

      有一个名为func_num_args() 的函数用于显示一个函数接收到多少个参数。

      这个简短的示例应该让您了解如何实现它:

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

      输出:

      Error!
      

      打来电话

      testfunc(1,2)
      

      输出:

      Arg1 => 1, Arg2 => 2
      

      【讨论】:

        猜你喜欢
        • 2012-08-26
        • 2012-05-23
        • 1970-01-01
        • 1970-01-01
        • 2013-01-05
        • 2022-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多