Call PHP function from string stored in a Variable

By Game Changer → Sunday, December 6, 2015

Do you need call a dynamic function?

Defined in your script.. Need Calling Dynamically?

Use call_user_func() instead:
//for normal function 
call_user_func($myVar);
// if hello() is in the current namespace
call_user_func(__NAMESPACE__.'\\'.$myVar);

// if hello() is in another namespace
call_user_func('mynamespace\\'.$myVar);

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();"


Dynamic Writing?

Following code can help to write dynamic function in PHP. now the function name can be dynamically change by variable '$current_page'.
$current_page = 'home_page';
$function = @${$current_page . '_page_versions'};
$function = function() {
    echo 'current page';
};
$function();

Sael

I'm Sael. An expert coder and system admin. I enjoy to make codes easy for novice.

Website: fb/Fujael

No Comment to " Call PHP function from string stored in a Variable "