Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 () {     //code here }  $functionName = "foo"; // I need to call the function based on what is $functionName 
like image 379
Lizard Avatar asked Jun 17 '09 08:06

Lizard


People also ask

How do you call a function with a variable?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var ); call_user_func( $var1 , "fun_function" );

How do you call a function which is stored in a variable?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

Can you use a string to call a function?

In summary, to call a function from a string, the functions getattr() , locals() , and globals() are used. getattr() will require you to know what object or module the function is located in, while locals() and globals() will locate the function within its own scope.

How can I call a function given its name as a string in C?

Put all the functions you want to select from into a dll, then use dlsym (or GetProcAddress on Windows, or whatever other API your system offers) to get the function pointer by name, and call using that.


1 Answers

$functionName() or call_user_func($functionName)

like image 67
knittl Avatar answered Oct 01 '22 11:10

knittl