Reputation: 6882
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?
Upvotes: 2
Views: 123
Reputation: 69937
Default function arguments can only take constant values, not expressions that are evaluated at runtime so your second option won't work.
One idea I have would be something like this.
function foo($user_id = null) {
$data = get_defaults('user_id' => $user_id);
extract($data);
echo $user_id; // should be the value returned from get_defaults()
}
The get_defaults()
function might look like this:
function get_defaults(array $params) {
if (isset($params['user_id']) && is_null($params['user_id'])) {
$params['user_id'] = get_id_from_session();
}
if (isset($params['something_else']) && !isValidSomething($params['something_else'])) {
$params['something_else'] = get_something_else();
}
return $params;
}
You would just pass an array to the get_defaults()
function based on the arguments the specific called function expects. So another example would be:
function bar($baz, $user_id = null, $user_name = null, $return = null) {
$data = get_defaults(array('return' => $return,
'user_name' => $user_name,
'user_id' => $user_id));
extract($data);
// normal function code below
}
Upvotes: 3
Reputation: 59699
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.
Upvotes: 4