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

自作多情 提交于 2019-12-20 03:38:11

问题


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.


回答1:


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
}



回答2:


I would rather give a Null value for this argument and then call loadDefaultUser() in the body of the function. Something like this:

function readUser($aUser = NULL){
    if(is_null($aUser)){
        $aUser = loadDefaultUser();
    }
    //...
}



回答3:


You can add a callback-parameter to your loadDefaultUser() function when it's finished it fires the callback function with the return/result. It's a bit like ajax-javascript callbacks.

function loadDefaultUser ( $callback ) 
{
   $result = true;       
   return $callback($result);
}



回答4:


function readUser($aUser = NULL){
   if ($aUser === NULL){
        $aUser = loadDefaultUser();
   }

   //do your stuff
}


来源:https://stackoverflow.com/questions/7050714/can-i-use-a-function-to-return-a-default-param-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!