A great thing about Python is that it can pass parameters to a function by name. it looks like this: 1my_foo_function (param_name = & quot; value & quot;, another_param_name = & quot; anothervalue & quot;) today I want to do the same thing in PHP5.4 (it can be easily transplanted.
A great thing about Python is that it can pass parameters to a function by name, which looks like this:
My_foo_function (param_name = "value", another_param_name = "another value ")
Today, I want to do the same thing in PHP 5.4 (which can be easily transplanted to PHP 5.3). I wrote a call_user_func_named function, similar to the built-in call_user_func_array function in PHP. the code is as follows:
$ 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
Update: Thanks to some enthusiastic contributors for their improvements:
$ 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