Call a PHP function dynamically

后端 未结 6 1405
[愿得一人]
[愿得一人] 2020-12-18 19:22

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         


        
6条回答
  •  情深已故
    2020-12-18 20:05

    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.

提交回复
热议问题