How to set optional parameter to default without passing it?

前端 未结 4 1822
一生所求
一生所求 2020-12-12 02:27

How can i skip first argument without giving any value in function call,so that first argument can take default value NULL?

function test($a = NULL, $b = tru         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 03:00

    You cannot just skip an argument in PHP.

    You may wish to consider the Perl trick and use an associated array. Use array_merge to merge the parameters with the defaults.

    e.g.

    function Test($parameters = null)
    {
       $defaults = array('color' => 'red', 'otherparm' => 5);
       if ($parameters == null)
       {
          $parameters = $defaults;
       }
       else
       {
          $parameters = array_merge($defaults, $parameters);
       }
     }
    

    Then call the function like this

    Test(array('otherparm' => 7));
    

提交回复
热议问题