我从这里找到了问题。但我需要用参数调用函数名。我需要能够调用一个函数,但是函数名存储在一个变量中,这是可能的吗?例如:
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
任何帮助都会很感激。
可以使用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));
我需要调用像$this->function_name这样的函数,我该怎么做?
@萨迪卡桑,请出示我编辑过的答案。
如果要使用参数动态调用函数,可以尝试如下操作:
function foo ($argument)
{
//code here
}
call_user_func('foo',"argument"); // php library funtion
希望对你有帮助。
我需要调用像$this->function_name这样的函数,我该怎么做?
哇,一个拥有4枚金牌的用户不会有这样的问题。你的代码已经工作了
function foo ($argument)
{
echo $argument;
}
function bar ($argument)
{
//code here
}
$functionName ="foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)
?>
产量
Joke
小提琴
从理论上讲,这种函数叫做变量函数
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
我需要调用像$this->function_name这样的函数,我该怎么做?
这也可以,只要稍加修改。$this->$functionName();
对不起的!问个愚蠢的问题,但这对我的项目来说很紧急。不管怎样,它工作得很好。谢谢
这个问题本身并不愚蠢,是个好问题。但真正不酷的是,你已经编写了可工作的代码,而不是尝试它,而是继续让其他人运行它:)