Using PHP optional function parameters

August 4, 2008 / Filed under: PHP, Code, Development, Tips

For a long time, I never knew why you'd want to set a functions' parameter equal to a value, in the function declaration:


function my_function($one, $two = false)
{
    ...
}

Notice the parameter $two is already set to 'false' within the function declaration.

I used to ask myself, if $two is always 'false' to begin with, why bother setting it there at all?

There could be many reasons, but one such reason came to me recently.

Since $two is already set to a value in the function declaration, you don't need to include that parameter in all function calls. In other words, it's an optional parameter. If you don't include it with your call to my_function, it will be set to 'false' by default.

So why is an optional parameter useful? Well, for one thing, if you add an additional parameter to my_function after you've already been using it everywhere in your application, you'd have to find every call to my_function and add that additional parameter, otherwise PHP will complain that you're missing a parameter.

With optional parameters, you don't have to worry about that. You can add a bunch of new parameters to the function declaration, and as long as they are set to a value, your existing calls to my_function remain intact and, well... functional!

Comments/Mentions