我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
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
当前回答
我想到的一种非常规方法是,除非你是通过一些超级超级自主的AI来生成整个代码,否则你想要“动态”调用的函数很有可能已经在你的代码库中定义了。所以为什么不只是检查字符串,并做臭名昭著的ifelse舞蹈来召唤…你明白我的意思了。
eg.
if($functionName == 'foo'){
foo();
} else if($functionName == 'bar'){
bar();
}
如果你不喜欢ifelse梯子的无味味道,甚至可以使用开关盒。
我知道在某些情况下,“动态调用函数”是绝对必要的(就像一些修改自身的递归逻辑)。但是大多数日常琐碎的用例都可以被避开。
它从应用程序中清除了许多不确定性,同时如果字符串不匹配任何可用函数的定义,则为您提供了执行回退函数的机会。恕我直言。
其他回答
如前所述,有几种方法可以实现这一点,最安全的方法可能是call_user_func(),如果必须,也可以使用$function_name()。可以这样使用这两种方法传递参数
$function_name = 'foobar';
$function_name(arg1, arg2);
call_user_func_array($function_name, array(arg1, arg2));
如果你调用的函数属于一个对象,你仍然可以使用它们中的任何一个
$object->$function_name(arg1, arg2);
call_user_func_array(array($object, $function_name), array(arg1, arg2));
然而,如果您打算使用$function_name()方法,如果名称是动态的,那么测试函数是否存在可能是个好主意
if(method_exists($object, $function_name))
{
$object->$function_name(arg1, arg2);
}
是的,这是可能的:
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
使用call_user_func函数。
补充@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"
我在这里举了另一个例子
我最喜欢的版本是内联版本:
${"variableName"} = 12;
$className->{"propertyName"};
$className->{"methodName"}();
StaticClass::${"propertyName"};
StaticClass::{"methodName"}();
你也可以把变量或表达式放在括号里!