简体   繁体   English

动态PHP功能

[英]Dynamic php function

How can we declare the function name dynamically? 如何动态声明函数名称?

For example : 例如 :

$function = 'test'
public $function(){

}

You could use a callback for this: 您可以为此使用回调:

https://stackoverflow.com/a/2523807/3887342 https://stackoverflow.com/a/2523807/3887342

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});

Declaring a function with a variable but arbitrary name like this is not possible without getting your hands dirty with eval() or include(). 如果不使用eval()或include()弄脏手,就无法用这样的变量但具有任意名称声明函数。

I think based on what you're trying to do, you'll want to store an anonymous function in that variable instead (use create_function() if you're not on PHP 5.3+): 我认为,根据您要执行的操作,您想将一个匿名函数存储在该变量中(如果您不在PHP 5.3+上,请使用create_function()):

$variableA = function() {
    // Do stuff
};

You can still call it as you would any variable function , like so: 您仍然可以像调用任何变量函数一样调用它,如下所示:

$variableA();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM