The great thing about Python is that it's able to pass arguments to a function using a 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 (easy to migrate to PHP 5.3), I wrote a call_user_func_named function, similar to the PHP built-in Call_user_func_array function, the code is as follows:
<?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, []); Would throw exception
Update: Thanks to some enthusiastic contributors for some improvements:
<?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) {
&nb Sp 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, []); Would throw exception
$y = Make_named_array_function ($x);
$y ([' foo ' => ' hello ', ' bar ' => ' world ')]; Pass All Parameterss
$y ([' Bar ' => ' world ']); Only pass one parameter
$y ([]); Would throw exception