Wednesday, July 18, 2018

Can I use a function to return a default param in php?



I would like to do something like this:




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.


Answer



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.



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
}


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...