我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
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"}();
你也可以把变量或表达式放在括号里!
如前所述,有几种方法可以实现这一点,最安全的方法可能是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
动态函数名和命名空间
只是在使用名称空间时补充一点关于动态函数名的内容。
如果你正在使用命名空间,下面的代码将不起作用,除非你的函数在全局命名空间中:
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);
如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:
$this->{$variable}();