PHP Function Arguments - Use an array or not?

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

提交回复
热议问题