我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:

function foo ()
{
    //code here
}

function bar ()
{
    //code here
}

$functionName = "foo";
// I need to call the function based on what is $functionName

当前回答

如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:

$this->{$variable}();

其他回答

是的,这是可能的:

function foo($msg) {
    echo $msg."<br />";
}
$var1 = "foo";
$var1("testing 1,2,3");

来源:http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2

如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:

$this->{$variable}();

我最喜欢的版本是内联版本:

${"variableName"} = 12;

$className->{"propertyName"};
$className->{"methodName"}();

StaticClass::${"propertyName"};
StaticClass::{"methodName"}();

你也可以把变量或表达式放在括号里!

$functionName()或call_user_func($functionName)

使用call_user_func函数。