动态调用 PHP 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4646991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:50:49  来源:igfitidea点击:

Call a PHP function dynamically

php

提问by nuttynibbles

Is there a way to call a function through variables?

有没有办法通过变量调用函数?

For instance, I want to call the function Login(). Can I do this:

例如,我想调用函数 Login()。我可以这样做吗:

$varFunction = "Login"; //to call the function

Can I use $varFunction?

我可以使用 $varFunction 吗?

回答by maartenba

Yes, you can:

是的你可以:

$varFunction();

Or:

或者:

call_user_func($varFunction);

Ensure that you validate $varFunction for malicious input.

确保您验证 $varFunction 是否存在恶意输入。



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.

然后使用正确的模块实例调用 runModuleMain()。

回答by alex

You can use...

您可以使用...

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

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

……不用说,要确保该变量是可信的。

回答by Andreyco

 <?php
  $fxname = 'helloWorld';

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

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

回答by Andreyco

I successfully call the function as follows:

我成功地调用了该函数,如下所示:

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

It works with PHP 5.3.0+

它适用于 PHP 5.3.0+

I'm also working in Laravel.

我也在 Laravel 工作。

回答by Dennis Kreminsky

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 closuresthat are dynamic anonymous functions, which could provide you with an alternative way to do what you want.

在该主题上,除了调用上述方法(即使用变量作为函数名或call_user_func_* 函数系列)之外,从 PHP 5.3 开始,您可以使用动态匿名函数的闭包,这可以为您提供另一种方式做你想做的事。