PHP Function Arguments - Use an array or not?

前端 未结 9 1649
挽巷
挽巷 2021-02-04 11:32

I like creating my PHP functions using key=>value pairs (arrays) as arguments instead of individual parameters.

For example, I prefer:

function useless_         


        
9条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 12:25

    Your co-worker is crazy. It's perfectly acceptable to pass in an array as a function argument. It's prevalent in many open source applications including Symfony and Doctrine. I've always followed the 2 argument rule, if a function needs more than two arguments, OR you think it will use more than two arguments in the future, use an array. IMO this allows for the most flexibility and reduces any calling code defects which may arise if an argument is passed incorrectly.

    Sure it takes a little bit more work to extrapolate the values from the array, and you do have to account for required elements, but it does make adding features much easier, and is far better than passing 13 arguments to the function every time it needs to be called.

    Here is a snippet of code displaying the required vs optional params just to give you an idea:

    // Class will tokenize a string based on params
    public static function tokenize(array $params)
    {
        // Validate required elements
        if (!array_key_exists('value', $params)) {
            throw new Exception(sprintf('Invalid $value: %s', serialize($params)));
        }        
    
        // Localize optional elements
        $value            = $params['value'];
        $separator        = (array_key_exists('separator', $params)) ? $params['separator'] : '-';
        $urlEncode        = (array_key_exists('urlEncode', $params)) ? $params['urlEncode'] : false;
        $allowedChars     = (array_key_exists('allowedChars', $params)) ? $params['allowedChars'] : array();
        $charsToRemove    = (array_key_exists('charsToRemove', $params)) ? $params['charsToRemove'] : array();
    
    ....
    

提交回复
热议问题