Call a PHP function dynamically

You can use...

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

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


 <?php
  $fxname = 'helloWorld';

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

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

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.

Tags:

Php