PHP Function with Optional Parameters

前端 未结 14 1140
星月不相逢
星月不相逢 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:13

    What I have done in this case is pass an array, where the key is the parameter name, and the value is the value.

    $optional = array(
      "param" => $param1,
      "param2" => $param2
    );
    
    function func($required, $requiredTwo, $optional) {
      if(isset($optional["param2"])) {
        doWork();
      }
    }
    
    0 讨论(0)
  • 2020-12-02 08:15

    If only two values are required to create the object with a valid state, you could simply remove all the other optional arguments and provide setters for them (unless you dont want them to changed at runtime). Then just instantiate the object with the two required arguments and set the others as needed through the setter.

    Further reading

    • Martin Fowler on Constructor vs Setter Injection and
    • Dependency injection through constructors or property setters?
    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-12-02 08:16

    You can just set the default value to null.

    <?php
    function functionName($value, $value2 = null) {
    // do stuff
    }
    
    0 讨论(0)
  • 2020-12-02 08:17

    I think, you can use objects as params-transportes, too.

    $myParam = new stdClass();
    $myParam->optParam2 = 'something';
    $myParam->optParam8 = 3;
    theFunction($myParam);
    
    function theFunction($fparam){      
      return "I got ".$fparam->optParam8." of ".$fparam->optParam2." received!";
    }
    

    Of course, you have to set default values for "optParam8" and "optParam2" in this function, in other case you will get "Notice: Undefined property: stdClass::$optParam2"

    If using arrays as function parameters, I like this way to set default values:

    function theFunction($fparam){
       $default = array(
          'opt1' => 'nothing',
          'opt2' => 1
       );
       if(is_array($fparam)){
          $fparam = array_merge($default, $fparam);
       }else{
          $fparam = $default;
       }
       //now, the default values are overwritten by these passed by $fparam
       return "I received ".$fparam['opt1']." and ".$fparam['opt2']."!";
    }
    
    0 讨论(0)
  • 2020-12-02 08:17

    I know this is an old post, but i was having a problem like the OP and this is what i came up with.

    Example of array you could pass. You could re order this if a particular order was required, but for this question this will do what is asked.

    $argument_set = array (8 => 'lots', 5 => 'of', 1 => 'data', 2 => 'here');
    

    This is manageable, easy to read and the data extraction points can be added and removed at a moments notice anywhere in coding and still avoid a massive rewrite. I used integer keys to tally with the OP original question but string keys could be used just as easily. In fact for readability I would advise it.

    Stick this in an external file for ease

    function unknown_number_arguments($argument_set) {
    
        foreach ($argument_set as $key => $value) {
    
            # create a switch with all the cases you need. as you loop the array 
            # keys only your submitted $keys values will be found with the switch. 
            switch ($key) {
                case 1:
                    # do stuff with $value
                    break;
                case 2:
                    # do stuff with $value;
                    break;
                case 3:
                    # key 3 omitted, this wont execute 
                    break;
                case 5:
                    # do stuff with $value;
                    break;
                case 8:
                    # do stuff with $value;
                    break;
                default:
                    # no match from the array, do error logging?
                    break;
            }
        }
    return;
    }
    

    put this at the start if the file.

    $argument_set = array(); 
    

    Just use these to assign the next piece of data use numbering/naming according to where the data is coming from.

    $argument_set[1][] = $some_variable; 
    

    And finally pass the array

    unknown_number_arguments($argument_set);
    
    0 讨论(0)
提交回复
热议问题