PHP Function Arguments - Use an array or not?

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

    Using array_merge() works okay, but using the + operator can be used too; it works the other way, it only adds default values where one hasn't been given yet.

    function useless_func(array $params = array())
    {
        $params += array(
            'text' => 'default text',
            'text2' => 'default text2',
            'text3' => 'default text3',
        );
    }
    

    See also: Function Passing array to defined key

    A few things you don't get with using arrays as function arguments is:

    1. type checking (only applicable to objects and arrays, but it can be useful and in some cases expected).
    2. smart(er) text editors have a code insight feature that will show the arguments a function understands; using arrays takes away that feature, though you could add the possible keys in the function docblock.
    3. due to #2 it actually becomes more error prone, because you might mistype the array key.

提交回复
热议问题