Skip to content

Instantly share code, notes, and snippets.

@shepik
Forked from beezee/param_call.php
Created July 1, 2012 19:07
Show Gist options
  • Save shepik/3029279 to your computer and use it in GitHub Desktop.
Save shepik/3029279 to your computer and use it in GitHub Desktop.
PHP named parameter calling
<?php
$x = function($bar, $foo="9") {
echo $foo, $bar, "\n";
};
class MissingArgumentException extends Exception {
}
function call_user_func_named_array($method, $arr){
$ref = new ReflectionFunction($method);
$params = [];
foreach( $ref->getParameters() as $p ){
if (!$p->isOptional() and !isset($arr[$p->name])) throw new MissingArgumentException("Missing parameter $p->name");
if (!isset($arr[$p->name])) $params[] = $p->getDefaultValue();
else $params[] = $arr[$p->name];
}
return $ref->invokeArgs( $params );
}
function make_named_array_function($func) {
return function($arr) use ($func) {
return call_user_func_named_array($func,$arr);
};
}
call_user_func_named_array($x, ['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss
call_user_func_named_array($x, ['bar' => 'world']); //Only pass one parameter
call_user_func_named_array($x, []); //Will throw exception
$y = make_named_array_function($x);
$y(['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss
$y(['bar' => 'world']); //Only pass one parameter
$y([]); //Will throw exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment