我可以使用函数在php中返回默认参数吗? [英] Can I use a function to return a default param in php?
本文介绍了我可以使用函数在php中返回默认参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做这样的事情:
function readUser($aUser = loadDefaultUser()){
//doing read User
}
我发现它将显示给我一个错误,如何传递函数返回值作为默认值?谢谢。
I find that it will display a error to me, how can I pass a function return as a default value? Thank you.
推荐答案
是的,您可以提供默认参数。但是,默认参数必须是常量表达式,而不是(例如)变量,类成员或函数调用。
Yes, you can provide a default argument. However, the default argument "must be a constant expression, not (for example) a variable, a class member or a function call."
您可以通过以下方式来伪造此行为:使用默认的某个常量值,然后在调用函数时将其替换为函数调用的结果。
You can fake this behaviour by using some constant value for the default, then replacing it with the results of a function call when the function is invoked.
我们将使用 NULL
,因为这是一个非常典型的无值值:
We'll use NULL
, since that's a pretty typical "no value" value:
function readUser($aUser = NULL) {
if (is_null($aUser))
$aUser = loadDefaultUser();
// ... your code here
}
这篇关于我可以使用函数在php中返回默认参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文