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
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.
- Social network etiquette: always follow up with new friends
- Twitter updates now mine
- Football weekly blame game
Similar Entries
- PHP: Skipping index page call in URL (149 recent visits)
- PHP project: convert times to numbers (303 recent visits)
- PHP – passing variables across pages (8656 recent visits)
- Install Apache, PHP, MySQL on Windows (169 recent visits)
- Code mnemonics: PHP implode/explode (383 recent visits)
- Swap banner image with CSS and PHP (660 recent visits)
Stats
634 unique visits since August 2008
Recent Referrers (click)
- php specify optional parameter
- optional parameter function argument php
- php functional parameter optional
- php optional parameter
- php optional arguments
- php + specify parameters to function
- optional arguments in functions PHP
- optional arguments in functions PHP
- php function optional input
- php function arguments
- php function arguments
- php optional parameters
- php optional parameters
- php function parameters optional
- php pass optional parameters