PHP Function with Optional Parameters

前端 未结 14 1194
星月不相逢
星月不相逢 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: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);
    

提交回复
热议问题