7 ms·
I think it is a useful construct for specifically the scenario it is mis-used in here. Overriding default values, or a kwargs polyfill function foo($option
by thefreeman 12y ago
I think it is a useful construct for specifically the scenario it is mis-used in here. Overriding default values, or a kwargs polyfill
function foo($option1=1, $option2=2, $option3=3, $option4=4) {
//do stuff with params
}
this is unwieldy and difficult to reason about when you see it used, especially if you are trying to use some of the initial default values. ie.
foo(null, null, null, 10)
vs.
function foo($options) {
$option1 = 1;
$option2 = 2;
$option3 = 3;
$option4 = 4;
extract($options);
//do stuff with params
}
With this, you can just do
foo(array('option4'=>10));
obviously its a preference thing, but I think it is a somewhat harmless use case. If there are any params which you do not want to be overriden you move them beneath the call to extract.
- ceejayoz 12y agoWe typically handle that by having a $defaults array, then array_merge($defaults, $options) in the function.
- thefreeman 12y agoYep, totally valid, and like I said basically a preference thing. I personally like to work with explicit variables within the function rather then array indices. With your system I could easily call extract on your resulting array, but I also like defining the variables I want overridden explicitly in code so I my IDE doesn't think they are undefined (though JetBrains does a pretty good job of determining which variables are being created by extract in most scenarios anyway).