Is there a way to call a function through variables?
For instance, I want to call the function Login(). Can I do this:
$varFunction = "Login"; //to call the function
Can I use $varFunction?
To do so, we can call any method dynamically. To call a method dynamically means that we can assign method name to any variable and call the method using that variable, either in switch case of if else block or anywhere depending on our requirement.
Dynamic Function Calls It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
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 );
Dynamic function calls are useful when you want to alter program flow according to changing circumstances. We might want our script to behave differently according to a parameter set in a URL's query string, for example. We can extract the value of this parameter and use it to call one of a number of functions.
Yes, you can:
$varFunction();
Or:
call_user_func($varFunction);
Ensure that you validate $varFunction for malicious input.
For your modules, consider something like this (depending on your actual needs):
abstract class ModuleBase { public function main() { echo 'main on base'; } } class ModuleA extends ModuleBase { public function main() { parent::main(); echo 'a'; } } class ModuleB extends ModuleBase { public function main() { parent::main(); echo 'b'; } } function runModuleMain(ModuleBase $module) { $module->main(); }
And then call runModuleMain() with the correct module instance.
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