php调用字符串函数参数,如何从包含参数的变量中存储的字符串调用PHP函数

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

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();

对不起的!问个愚蠢的问题,但这对我的项目来说很紧急。不管怎样,它工作得很好。谢谢

这个问题本身并不愚蠢,是个好问题。但真正不酷的是,你已经编写了可工作的代码,而不是尝试它,而是继续让其他人运行它:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值