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();
對不起的!問個愚蠢的問題,但這對我的項目來說很緊急。不管怎樣,它工作得很好。謝謝
這個問題本身并不愚蠢,是個好問題。但真正不酷的是,你已經編寫了可工作的代碼,而不是嘗試它,而是繼續讓其他人運行它:)
總結
以上是生活随笔為你收集整理的php调用字符串函数参数,如何从包含参数的变量中存储的字符串调用PHP函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 凤凰式期权matlab代码,美式期权二叉
- 下一篇: 动态规划算法php,php算法学习之动态