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

后端 未结 16 2301
予麋鹿
予麋鹿 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:12

    For the sake of completeness, you can also use eval():

    $functionName = "foo()";
    eval($functionName);
    

    However, call_user_func() is the proper way.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-11-22 11:17

    Yes, it is possible:

    function foo($msg) {
        echo $msg."<br />";
    }
    $var1 = "foo";
    $var1("testing 1,2,3");
    

    Source: http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2

    0 讨论(0)
  • 2020-11-22 11:17

    A few years late, but this is the best manner now imho:

    $x = (new ReflectionFunction("foo"))->getClosure();
    $x();
    
    0 讨论(0)
提交回复
热议问题