动态调用PHP函数 [英] Call a PHP function dynamically
本文介绍了动态调用PHP函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以通过变量调用函数?
Is there a way to call a function through variables?
例如,我想调用函数Login().我可以这样做吗?
For instance, I want to call the function Login(). Can I do this:
$varFunction = "Login"; //to call the function
我可以使用$ varFunction吗?
Can I use $varFunction?
推荐答案
是的,您可以:
$varFunction();
或者:
call_user_func($varFunction);
确保您对$ 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();
}
然后使用正确的模块实例调用runModuleMain().
And then call runModuleMain() with the correct module instance.
这篇关于动态调用PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文