Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this questionFirstly, I want to say I'm not trying to start a war here. I'm aware there can be some strongly held opinions from my own conversations on the topic that follows so I am looking for an answer that outlines the pros and cons.
In loosely typed languages (and I'm specifically coming from a PHP standpoint), there are two ways, in design terms, to pass parameters (note, I'm not talking about getting the parameters within the called functions).
On the one hand you can pass them as individual parameters as below:
foo($var1, $var2, $var3 ...);
On the other hand you can package up your variables into an array and then pass a single argument to the function, the array:
$bar[] = $var1;
$bar[] = $var2;
$bar[] = $var3;
...
foo($bar);
I can see the benefit of the second method when you have a lot of variables that need to be handled in a generic way, however, it also hides what variables the function needs in order to operate correctly.
The first solution, while it quickly becomes a long function call as the number of variables increases, better shows what variables the function requires and enables leveraging functionality to assign a default value if a null value is passed in the function call.
So, under what circumstances should one or the other be used and what about the middle ground, where for example, the array is associative so you can get the variables out by name inside the function and use them in a non-generic way? To me the associative array scenario seems开发者_开发问答 very un-optimal and is simply a way that some developers use to make the function call itself shorter while actually increasing the overall amount of code written.
I think that your example of passing an array is pretty pointless. If you do this you should definitely pass the arguments using the normal way.
Passing an array is only useful if a function accepts several optional parameters which could be passed in pretty much any order:
function x($width = 100, $height = 100, $color = 'red')
Here, in case you want to change the color, but not change the default width and height you would need to do:
x(100, 100, 'blue');
I.e. you would need to copy the default values in your code.
Instead one could declare the function as follows:
function x(array $opts) {
$opts += array('width' => 100, 'height' => 100, 'color' => 'red');
}
x(array('color' => 'blue'));
For a more real-life example, have a look at the constructor of Twig_Environment
: As you can see, there are quite some options, most of them you will probably want to be kept at their default value. If you had to pass all of this options as an argument, you would just bloat the code by copying default values.
精彩评论