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

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

    Dynamic function names and namespaces

    Just to add a point about dynamic function names when using namespaces.

    If you're using namespaces, the following won't work except if your function is in the global namespace:

    namespace greetings;
    
    function hello()
    {
        // do something
    }
    
    $myvar = "hello";
    $myvar(); // interpreted as "\hello();"
    

    What to do?

    You have to use call_user_func() instead:

    // if hello() is in the current namespace
    call_user_func(__NAMESPACE__.'\\'.$myvar);
    
    // if hello() is in another namespace
    call_user_func('mynamespace\\'.$myvar);
    

提交回复
热议问题