PHP Function Arguments - Use an array or not?

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

    Don't do that!

    Passing all in an array is a bad idea most of the time.

    • It prevents people from using your function without knowing what it needs to operate.
    • It lets you create functions needing lots of parameters when probably you should create a function with more precise argument needs and a narrower goal

    It seems like the contrary of injecting in a function what it needs.

    Function arguments can be provided in any order

    I have no such preference. I don't understand that need.

    Easier to read code / more self documenting (in my opinion)

    Most IDEs will present you with the different arguments a function needs. If one sees a function declaration like foo(Someclass $class, array $params, $id) it is very clear what the function needs. I disagree that a single param argument is easier to read or self documenting.

    Less prone to errors, because when calling a function I must investigate the proper array keys

    Allowing people to pass in an array without knowing that values will be defaulted is not close to "not error-prone". Making it mandatory for people to read your function before using it is a sure way for it never to be used. Stating that it needs three arguments along with their defaults is less error prone because people calling your function will know which values the parameters will be defaulted to, and trust that it will present the result they expect.


    If the problem you are trying to solve is a too great number of arguments, the right decision is to refactor your functions into smaller ones, not hide function dependencies behind an array.

提交回复
热议问题