vendredi 13 mai 2016

How to dynamically call PHP method and pass multiple variables not in an array?

I want to be able to call a php function, but only if the number of elements input, matches the number of elements accepted by the function and if it does match i want to pass them 1 by 1 and not as an array.

Currently i have the following code which does the job, but is messy.

call_user_func($functionname, $vars);

This was hitting problems when i had a function that expected an array of 4 elements, but was only passed 3. Having to check and make sure all the vars exist makes writing functions a bit messy. I have a better solution based on reflection. how to dynamically check number of arguments of a function in php , but im one final step short. If the number of arguments matches the number of arguments in a function, i can call that method, but i dont know how to call that method correctly. I have an array of variables. I need to pass these into the function so that I can do something like the following.

function foo($var1, $var2, $var3)
{
    //I know all 3 vars exist and dont need to verify first
}
if(count($arrayof3elements) == get_method_var_count("foo") {
    dynamically_call_method("foo", $arrayof3elements);
}





Aucun commentaire:

Enregistrer un commentaire