如何从带参数的变量中存储的字符串中调用PHP函数


How to call PHP function from string stored in a Variable with arguments

我从这里找到了问题。但我需要用参数调用函数名。我需要能够调用一个函数,但函数名存储在一个变量中,这可能吗?例如:

function foo ($argument)
{
  //code here
}
function bar ($argument)
{
  //code here
}
$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName

任何帮助都将不胜感激。

哇,没有人会想到一个拥有4枚金牌的用户会提出这样的问题。你的代码已经工作

<?php
function foo ($argument)
{
  echo $argument;
}
function bar ($argument)
{
  //code here
}
$functionName = "foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)
?>

输出

笑话

Fiddle

现在从理论上讲,这种函数被称为可变函数

PHP支持变量函数的概念。这意味着,如果变量名后面附加了括号,PHP将查找与变量求值结果同名的函数,并尝试执行它。除其他外,这可以用于实现回调、函数表等。

如果你想用参数动态调用一个函数,那么你可以这样尝试:

function foo ($argument)
{
  //code here
}
call_user_func('foo', "argument"); // php library funtion

希望它能帮助你。

您可以使用php函数call_user_func。

function foo($argument)
{
    echo $argument;
}
$functionName = "foo";
$argument = "bar";
call_user_func($functionName, $argument);

如果你在一个类中,你可以使用call_user_func_array:

//pass as first parameter an array with the object, in this case the class itself ($this) and the function name
call_user_func_array(array($this, $functionName), array($argument1, $argument2));