我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName
我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName
当前回答
动态函数名和命名空间
只是在使用名称空间时补充一点关于动态函数名的内容。
如果你正在使用命名空间,下面的代码将不起作用,除非你的函数在全局命名空间中:
namespace greetings;
function hello()
{
// do something
}
$myvar = "hello";
$myvar(); // interpreted as "\hello();"
怎么办呢?
你必须使用call_user_func()来代替:
// if hello() is in the current namespace
call_user_func(__NAMESPACE__.'\\'.$myvar);
// if hello() is in another namespace
call_user_func('mynamespace\\'.$myvar);
其他回答
我最喜欢的版本是内联版本:
${"variableName"} = 12;
$className->{"propertyName"};
$className->{"methodName"}();
StaticClass::${"propertyName"};
StaticClass::{"methodName"}();
你也可以把变量或表达式放在括号里!
我不知道你为什么要用它,听起来对我来说一点都不好,但如果只有少量的函数,你可以使用if/elseif结构。 我不知道是否有直接的解决办法。
类似的 $foo = "bar"; $test = "foo"; echo $ $测试;
应该返回酒吧,你可以尝试,但我不认为这将工作的功能
补充@Chris K的回答,如果你想调用一个对象的方法,你可以在闭包的帮助下使用一个变量来调用它:
function get_method($object, $method){
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
class test{
function echo_this($text){
echo $text;
}
}
$test = new test();
$echo = get_method($test, 'echo_this');
$echo('Hello'); //Output is "Hello"
我在这里举了另一个例子
为了完整起见,你也可以使用eval():
$functionName = "foo()";
eval($functionName);
然而,call_user_func()是正确的方法。
使用call_user_func函数。