我可以使用函数在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
}