3 ms·
I'm often using compact()/extract() in similar, but not necessarily identical pattern. For example: $foo = get_some_value(); $bar = get_other_value(); my
by dexen 14y ago
I'm often using compact()/extract() in similar, but not necessarily identical pattern. For example:
$foo = get_some_value();
$bar = get_other_value();
my_function(compact('foo', 'bar'));
function my_function($args) {
# optionally provide default values :-)
$foo = default_value;
$bar = default_value;
extract($args, EXTR_IF_EXISTS); # the EXTR_IF_EXISTS is optional, for when we want to enforce sanity check
/* function code goes here */
}
(edits: clarifications)
- notJim 14y agoWhy? This is a horrible idea. It makes your code so much harder to read or reason about, because it's impossible to tell what variables will be passed in without looking at every single callsite.
- dexen 14y agoThat's not how the code works; I can assure you after using it for some time. The client code (the callee) is in control of variables and lists explicitly what will be provided, either as default or as an actual (keyword) argument. When using EXTR_IF_EXISTS and list of default values, you know exactly what variables you will get -- either passed as argument, or by default, by reading the callee. When not using EXTR_IF_EXISTS and you want to extract only known-good variables from untrusted input, array_intersect_key() helps. The idiom may seem strange at first, but once you get used to it, you read it naturally. That's the thing with idioms, after all. Point in case, our new hire got up to speed very quickly. ---- EDIT: in some cases I just skip the extract()ing and simply access $args['field_name']. It's safe as PHP will raise error, stop execution and drop to error handler if some field was not provided by mistake -- or malicious user action. And any superfluous fields remain unaccessed, safe again.