PHP Function Arguments - Use an array or not?

前端 未结 9 1520
挽巷
挽巷 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:07

    @Mike, you could also "extract()" your $params argument into local variables, like this:

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

    ....

    Same implementation, but shorter.

提交回复
热议问题