How to set optional parameter to default without passing it?

前端 未结 4 1813
一生所求
一生所求 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 02:46

    You can change the position of the arguments, or you can pass the arguments as an array, for exmaple:

    test($options);
    
    0 讨论(0)
  • 2020-12-12 02:46

    YOu have to use the format defined my the PHP function standards

    test("",false);
    

    The requirement you have works with jquery libraries...for arguments passing in its functions. But NOT in PHP

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-12-12 03:07

    Redifine your function as

        function test($b = true,$a = NULL){
     //logic here
    }
    

    And you can call it like test(5); avoiding second parameter.

    0 讨论(0)
提交回复
热议问题