I just wrote this function that lets you call a function by an associative array. I've only tested it on scalar types though, but it should work fine for functions which take in ints
, floats
, strings
, and booleans
. I wrote this quite fast and it can definitely be improved in more ways than one:
function call_user_func_assoc($function, $array){
$matches = array();
$result = array();
$length = preg_match_all('/Parameter #(\d+) \[ <(required|optional)> \$(\w+)(?: = (.*))? ]/', new ReflectionFunction($function), $matches);
for($i = 0; $i < $length; $i++){
if(isset($array[$matches[3][$i]]))
$result[$i] = $array[$matches[3][$i]];
else if($matches[2][$i] == 'optional')
$result[$i] = eval('return ' . $matches[4][$i] . ';');
else
throw new ErrorException('Missing required parameter: $' . $matches[3][$i]);
}
call_user_func_array($function, $result);
}
You can use it like this:
function basicFunction($var1, $var2 = "default string", $var3 = 2, $var4 = 5){
var_dump(func_get_args());
}
call_user_func_assoc('basicFunction', array('var1' => "Bob", 'var4' => 30));
Which outputs:
array(4) {
[0]=>
string(3) "Bob"
[1]=>
string(14) "default string"
[2]=>
int(2)
[3]=>
int(30)
}