How to call a function from a string stored in a variable?

后端 未结 16 2432
予麋鹿
予麋鹿 2020-11-22 10:16

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 ()
{
          


        
16条回答
  •  轮回少年
    2020-11-22 11:14

    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);
    }
    

提交回复
热议问题