PHP Function Arguments - Use an array or not?

前端 未结 9 1534
挽巷
挽巷 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.

    0 讨论(0)
  • 2021-02-04 12:06

    Well, it's kinda usefully. But for some arguments which is passing always it's better to use classic passing like function some($a1, $a2). I'm doing like this in my code:

    function getSome(SomeClass $object, array $options = array())
    {
        // $object is required to be an instance of SomeClass, and there's no need to get element by key, then check if it's an object and it's an instance of SomeClass
    
        // Set defaults for all passed options
        $options = array_merge(array(
            'property1' => 'default1',
            'property2' => 'default2',
            ... => ...
        ), $options); 
    }
    

    So, as you can see I like that code style too, but for core-arguments I prefer classic style, because that way PHP controls more things which should I, if I used the you code style.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2021-02-04 12:22

    This borders on Cargo Cult programming. You say this is more readable and self-documenting. I would ask how? To know how to use your function/method I have to read into the code itself. There's no way I can know how to use it from the signature itself. If you use any half-decent IDE or editor that supports method signature hinting this will be a real PITA. Plus you won't be able to use PHP's type-hinting syntax.

    If you find you are coding a load of parameters, especially optional parameters then it suggests there might be something wrong with your design. Consider how else you might go about it. If some or all of the parameters are related then maybe they belong to their own class.

    0 讨论(0)
  • 2021-02-04 12:23

    I have used arrays to substitute a long list of parameters in many occasions and it has worked well. I agree with those in this post that have mentioned about code editors not being able to provide hints for the arguments. Problem is that if I have 10 arguments, and the first 9 are blank/null it just becomes unwieldy when calling that function.

    I would also be interested in hearing an how to re-design a function that requires a lot of arguments. For example, when we have a function that builds SQL statements based on certain arguments being set:

    function ($a1, $a2, ... $a10){
    
            if($a1 == "Y"){$clause_1 = " something = ".$a1." AND ";}
            ...
            if($a10 == "Y"){$clause_10 = " something_else = ".$a10." AND ";}
    
            $sql = "
            SELECT * FROM some_table 
            WHERE
            ".$clause_1." 
            ....
            ".$clause_10." 
            some_column = 'N'
            ";
    
            return $sql;
        }
    

    I would like to see PHP entertain adding a native helper function that could be used within a the function being called that would assist in passing an array of parameters by undertaking the necessary type checking. PHP recognized this to a certain extent by creating the func_get_args() function which allows arguments to be passed in any order. BUT this will only pass a COPY of the values, so if you want to pass objects to the function this will be a problem. If such a function existed, then the code editors would be able to pick this up and provide details on possible arguments.

    0 讨论(0)
提交回复
热议问题