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
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" );
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.
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.
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.
$functionName()
or call_user_func($functionName)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With