5 ms·
compact() + extract() is the closest you get. $foo = 123; $bar = getSomeBar(); myFunction(compact('foo', 'bar')); function myFunction($kwargs) {
by dexen 15y ago
compact() + extract() is the closest you get.
$foo = 123;
$bar = getSomeBar();
myFunction(compact('foo', 'bar'));
function myFunction($kwargs) {
$foo = SOME_DEFAULT_VALUE;
extract($kwargs);
if ($foo > 5) {
...
}
}
If you want to `sanitize' which arguments can be passed that way, use extract(array_intersect_key($allowed, $kwargs)); ((EDIT: or use EXTR_IF_EXISTS)).
Nb., extract() works on any associative array, you don't have to use compact().
- cag_ii 15y agoWhy would this be any better than just passing in a map of the parameters as the sole parameter? myFunction($parms=array()) { ... } $parms = array('foo' => 'bar', 'baz' => 'yaz'); test($parms);
- dexen 15y agoConcise. Documented, standard and configurable handling of existing variables (may be used for default values etc.) via EXTR_OVERWRITE, EXTR_SKIP, etc. Documented, standard behavior of compact() in regard to missing variables. No manual associating of foo with $foo -- less places for mundane errors. Oh, and there's even that EXTR_IF_EXISTS -- so my silly idea to sanitize with array_intersect_keys() was totally unneeded. Make it $foo = 123; $bar = getSomeBar(); $coot = 'boot'; myFunc(compact('foo', 'bar', 'coot')); function myFunc($kwargs) { $foo = 1; $bar = 'xyz'; extract($kwargs, EXTR_IF_EXISTS); /* sanitization: $coot will NOT get extracted because the function doesn't expect / support that argument */ ... }
- underwater 15y agoIn case you weren't sure on this, it is exactly the same. Compact takes a list of variables names in the local scope and returns an associative array containing their values.