PHP Function with Optional Parameters

前端 未结 14 1193
星月不相逢
星月不相逢 2020-12-02 08:05

I\'ve written a PHP function that can accepts 10 parameters, but only 2 are required. Sometimes, I want to define the eighth parameter, but I don\'t want to type in empty st

14条回答
  •  萌比男神i
    2020-12-02 08:31

    NOTE: This is an old answer, for PHP 5.5 and below. PHP 5.6+ supports default arguments

    In PHP 5.5 and below, you can achieve this by using one of these 2 methods:

    • using the func_num_args() and func_get_arg() functions;
    • using NULL arguments;

    How to use

    function method_1()
    {
      $arg1 = (func_num_args() >= 1)? func_get_arg(0): "default_value_for_arg1";
      $arg2 = (func_num_args() >= 2)? func_get_arg(1): "default_value_for_arg2";
    }
    
    function method_2($arg1 = null, $arg2 = null)
    {
      $arg1 = $arg1? $arg1: "default_value_for_arg1";
      $arg2 = $arg2? $arg2: "default_value_for_arg2";
    }
    

    I prefer the second method because it's clean and easy to understand, but sometimes you may need the first method.

提交回复
热议问题