Skip to content

Instantly share code, notes, and snippets.

@maxpert
Created July 1, 2012 12:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save maxpert/3028283 to your computer and use it in GitHub Desktop.
Save maxpert/3028283 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() ){
if( isset($arr[$p->name]) ){
$params[] = $arr[$p->name];
}else{
$params[] = $p->getDefaultValue();
}
}else if( isset($arr[$p->name]) ){
$params[] = $arr[$p->name];
}else{
throw new MissingArgumentException("Missing parameter $p->name");
}
}
return $ref->invokeArgs( $params );
}
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment