Using PHP optional function parameters Aug04 '08

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!

Categories: Code , Development , PHP , Tips

Add Feedback (view all)

Leave feedback

Feedback

Input format: The editor controls below will assist with Markdown syntax.

Status

Sub-status

Your info

matthom is published and produced by Matt Thommes - an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from Chicago. Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.

Contact Matt

Similar Entries

Stats

634 unique visits since August 2008

Syndicate

Advertisements