我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:
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
当前回答
如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:
$this->{$variable}();
其他回答
考虑到这里给出的一些很好的答案,有时你需要精确。 为例。
如果一个函数有返回值,例如(boolean,array,string,int,float e.t.c)。 如果函数没有返回值,则检查 如果函数存在
让我们来看看这些答案的可信度。
Class Cars{
function carMake(){
return 'Toyota';
}
function carMakeYear(){
return 2020;
}
function estimatedPriceInDollar{
return 1500.89;
}
function colorList(){
return array("Black","Gold","Silver","Blue");
}
function carUsage(){
return array("Private","Commercial","Government");
}
function getCar(){
echo "Toyota Venza 2020 model private estimated price is 1500 USD";
}
}
我们想要检查方法是否存在并动态调用它。
$method = "color List";
$class = new Cars();
//If the function have return value;
$arrayColor = method_exists($class, str_replace(' ', "", $method)) ? call_user_func(array($this, $obj)) : [];
//If the function have no return value e.g echo,die,print e.t.c
$method = "get Car";
if(method_exists($class, str_replace(' ', "", $method))){
call_user_func(array($class, $method))
}
谢谢
虽然晚了几年,但我认为这是现在最好的方式:
$x = (new ReflectionFunction("foo"))->getClosure();
$x();
我想到的一种非常规方法是,除非你是通过一些超级超级自主的AI来生成整个代码,否则你想要“动态”调用的函数很有可能已经在你的代码库中定义了。所以为什么不只是检查字符串,并做臭名昭著的ifelse舞蹈来召唤…你明白我的意思了。
eg.
if($functionName == 'foo'){
foo();
} else if($functionName == 'bar'){
bar();
}
如果你不喜欢ifelse梯子的无味味道,甚至可以使用开关盒。
我知道在某些情况下,“动态调用函数”是绝对必要的(就像一些修改自身的递归逻辑)。但是大多数日常琐碎的用例都可以被避开。
它从应用程序中清除了许多不确定性,同时如果字符串不匹配任何可用函数的定义,则为您提供了执行回退函数的机会。恕我直言。
使用存储在变量中的名称安全地调用函数的最简单方法是,
//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);
}
为了完整起见,你也可以使用eval():
$functionName = "foo()";
eval($functionName);
然而,call_user_func()是正确的方法。