Search code examples
phpfunctionargumentsoptional-arguments

Function argument: default value return of a function?


I have lots of functions with optional arguments, which on an omitted value gets its default value from a specified function, currently my code looks something like this:

function get_user($user_id = FALSE) {

   // If no ID is passed, get from session
   if(!$user_id) { 
      $user_id = get_id_from_session();      
   }

   // ... do something with the ID
}

It works fine, but it easily gets very clutty when having more then one optional argument. Instead, I'd prefer to do something like the following:

function get_user($user_id = get_id_from_session()) {

   // ... do something with the ID

}

I'm sure that you can see how that is more convenient. Is there any way to accomplish this, or do anyone have suggestions on another cleaner approach to do this?


Solution

  • The only way that you can "shorten" this is to use the ternary operator:

    $user_id = ( $user_id === false) ? get_id_from_session() : $user_id;
    

    Which is just a compact version of writing:

    if( $user_id === false) {
        $user_id = get_id_from_session();
    }
    

    If you want to be real fancy and less-readable, you can omit the middle part (PHP > 5.3):

    $user_id = ( $user_id) ?: get_id_from_session();
    

    Now, if ( $user_id) evaluates to true, you'd get the value of $user_id in $user_id, otherwise you'd get the return value from the function.