Call a PHP function dynamically

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?

Answer

Solution:

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.

Answer

Solution:

You can use...

$varFunction = "Login";
$varFunction();

...and it goes without saying to make sure that the variable is trusted.

Answer

Solution:

 <?php
  $fxname = 'helloWorld';

  function helloWorld(){
    echo "What a beautiful world!";
  }

  $fxname(); //echos What a beautiful world!
?>

Answer

Solution:

I successfully call the function as follows:

$methodName = 'Login';
$classInstance = new ClassName();
$classInstance->$methodName($arg1, $arg2, $arg3);

It works with PHP 5.3.0+

I'm also working in Laravel.

Answer

Solution:

If it's in the same class:

$funcName = 'Login';

// Without arguments:
$this->$funcName();

// With arguments:
$this->$funcName($arg1, $arg2);

// Also acceptable:
$this->{$funcName}($arg1, $arg2)

If it's in a different class:

$someClass = new SomeClass(); // create new if it doesn't already exist in a variable
$someClass->$funcName($arg1, $arg2);

// Also acceptable:
$someClass->{$funcName}($arg1, $arg2)

Tip:

If the function name is dynamic as well:

$step = 2;

$this->{'handleStep' . $step}($arg1, $arg2);
// or
$someClass->{'handleStep' . $step}($arg1, $arg2);

This will call handleStep1(), handleStep2(), etc. depending on the value of $step.

Answer

Solution:

You really should consider using classes for modules, as this would allow you to both have consistent code structure and keep method names identical for several modules. This will also give you the flexibility in inheriting or changing the code for every module.

On the topic, other than calling methods as stated above (that is, using variables as function names, or call_user_func_* functions family), starting with PHP 5.3 you can use closures that are dynamic anonymous functions, which could provide you with an alternative way to do what you want.

Source