php调用字符串函数参数,如何从包含参数的变量中存储的字符串调用PHP函数
我從這里找到了問(wèn)題。但我需要用參數(shù)調(diào)用函數(shù)名。我需要能夠調(diào)用一個(gè)函數(shù),但是函數(shù)名存儲(chǔ)在一個(gè)變量中,這是可能的嗎?例如:
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
任何幫助都會(huì)很感激。
可以使用php函數(shù)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));
我需要調(diào)用像$this->function_name這樣的函數(shù),我該怎么做?
@薩迪卡桑,請(qǐng)出示我編輯過(guò)的答案。
如果要使用參數(shù)動(dòng)態(tài)調(diào)用函數(shù),可以嘗試如下操作:
function foo ($argument)
{
//code here
}
call_user_func('foo',"argument"); // php library funtion
希望對(duì)你有幫助。
我需要調(diào)用像$this->function_name這樣的函數(shù),我該怎么做?
哇,一個(gè)擁有4枚金牌的用戶不會(huì)有這樣的問(wèn)題。你的代碼已經(jīng)工作了
function foo ($argument)
{
echo $argument;
}
function bar ($argument)
{
//code here
}
$functionName ="foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)
?>
產(chǎn)量
Joke
小提琴
從理論上講,這種函數(shù)叫做變量函數(shù)
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.
我需要調(diào)用像$this->function_name這樣的函數(shù),我該怎么做?
這也可以,只要稍加修改。$this->$functionName();
對(duì)不起的!問(wèn)個(gè)愚蠢的問(wèn)題,但這對(duì)我的項(xiàng)目來(lái)說(shuō)很緊急。不管怎樣,它工作得很好。謝謝
這個(gè)問(wèn)題本身并不愚蠢,是個(gè)好問(wèn)題。但真正不酷的是,你已經(jīng)編寫(xiě)了可工作的代碼,而不是嘗試它,而是繼續(xù)讓其他人運(yùn)行它:)
總結(jié)
以上是生活随笔為你收集整理的php调用字符串函数参数,如何从包含参数的变量中存储的字符串调用PHP函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 凤凰式期权matlab代码,美式期权二叉
- 下一篇: 建模matlab的算法代码呀,数学建模算