I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
function foo () { //code here } function bar () {
As already mentioned, there are a few ways to achieve this with possibly the safest method being call_user_func()
or if you must you can also go down the route of $function_name()
. It is possible to pass arguments using both of these methods as so
$function_name = 'foobar';
$function_name(arg1, arg2);
call_user_func_array($function_name, array(arg1, arg2));
If the function you are calling belongs to an object you can still use either of these
$object->$function_name(arg1, arg2);
call_user_func_array(array($object, $function_name), array(arg1, arg2));
However if you are going to use the $function_name()
method it may be a good idea to test for the existence of the function if the name is in any way dynamic
if(method_exists($object, $function_name))
{
$object->$function_name(arg1, arg2);
}