Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a PHP function dynamically

Tags:

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?

like image 968
chrizonline Avatar asked Jan 10 '11 12:01

chrizonline


People also ask

How do you call a method dynamically in PHP?

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.

How can we call function dynamically in PHP explain it with an example?

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.

How do you call a PHP function?

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

What is dynamic function call?

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.


1 Answers

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.

like image 66
maartenba Avatar answered Oct 13 '22 11:10

maartenba