在 PHP 中使用变量作为函数名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8466473/
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-26 04:48:00  来源:igfitidea点击:

Use Variable as Function Name in PHP

phpfunctionvariables

提问by Carl Thomas

Possible Duplicate:
Use a variable to define a PHP function

可能的重复:
使用变量定义 PHP 函数

Is there a way of using a variable as a function name.

有没有办法使用变量作为函数名。

For example i have a variable

例如我有一个变量

$varibaleA;

and I want to create a function i.e.

我想创建一个函数,即

function $variableA() {
}

so this function can be called later in the script. Does anyone know if this can be done?

所以这个函数可以稍后在脚本中调用。有谁知道这是否可以做到?

Thanks

谢谢

回答by BoltClock

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 thinkbased on what you're trying to do, you'll want to store an anonymous functionin that variable instead (use create_function()if you're not on PHP 5.3+):

认为根据您要执行的操作,您需要在该变量中存储一个匿名函数create_function()如果您不是在 PHP 5.3+ 上使用):

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

You can still call it as you would any variable function, like so:

您仍然可以像调用任何变量 function一样调用它,如下所示:

$variableA();

回答by Marc B

$x = 'file_get_contents';
$html = $x('http://google.com');

is functionally equivalent to doing

在功能上等同于做

$html = file_get_contents('http://google.com');

They're called variable functions, and generally should be avoided as they're too far removed from variable variables.

它们被称为变量函数,通常应该避免,因为它们离变量变量太远了。

回答by Kakashi

you can do this:

你可以这样做:

$foo = function() {
    //..
};

and then:

进而:

$foo(); 

works in PHP 5.3+

适用于 PHP 5.3+