PHP Function with Optional Parameters

前端 未结 14 1211
星月不相逢
星月不相逢 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条回答
  •  青春惊慌失措
    2020-12-02 08:16

    To accomplish what you want, use an array Like Rabbot said (though this can become a pain to document/maintain if used excessively). Or just use the traditional optional args.

    //My function with tons of optional params
    function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
    {
      //Do stuff
    }
    my_func('Hi', 'World', null, null, 'Red');
    

    However, I usually find that when I start writing a function/method with that many arguments - more often than not it is a code smell, and can be re-factored/abstracted into something much cleaner.

    //Specialization of my_func - assuming my_func itself cannot be refactored
    function my_color_func($reg_a, $reg_b, $opt = 'Red')
    {
      return my_func($reg_a, $reg_b, null, null, $opt);
    }
    my_color_func('Hi', 'World');
    my_color_func('Hello', 'Universe', 'Green');
    

提交回复
热议问题