我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
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
当前回答
下面的代码有助于用PHP编写动态函数。 现在函数名可以通过变量'$current_page'动态更改。
$current_page = 'home_page';
$function = @${$current_page . '_page_versions'};
$function = function() {
echo 'current page';
};
$function();
其他回答
使用存储在变量中的名称安全地调用函数的最简单方法是,
//I want to call method deploy that is stored in functionname
$functionname = 'deploy';
$retVal = {$functionname}('parameters');
我使用如下方法在Laravel中动态创建迁移表,
foreach(App\Test::$columns as $name => $column){
$table->{$column[0]}($name);
}
我最喜欢的版本是内联版本:
${"variableName"} = 12;
$className->{"propertyName"};
$className->{"methodName"}();
StaticClass::${"propertyName"};
StaticClass::{"methodName"}();
你也可以把变量或表达式放在括号里!
如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:
$this->{$variable}();
动态函数名和命名空间
只是在使用名称空间时补充一点关于动态函数名的内容。
如果你正在使用命名空间,下面的代码将不起作用,除非你的函数在全局命名空间中:
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);
虽然晚了几年,但我认为这是现在最好的方式:
$x = (new ReflectionFunction("foo"))->getClosure();
$x();