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

后端 未结 4 975
予麋鹿
予麋鹿 2021-01-22 21:07

I would like to do something like this:

function readUser($aUser = loadDefaultUser()){

 //doing read User
}

I find that it will display a erro

相关标签:
4条回答
  • 2021-01-22 21:07

    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
    }
    
    0 讨论(0)
  • 2021-01-22 21:13

    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();
        }
        //...
    }
    
    0 讨论(0)
  • 2021-01-22 21:13

    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);
    }
    
    0 讨论(0)
  • 2021-01-22 21:19
    function readUser($aUser = NULL){
       if ($aUser === NULL){
            $aUser = loadDefaultUser();
       }
    
       //do your stuff
    }
    
    0 讨论(0)
提交回复
热议问题