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
- Gmail SMS: where are you?
Similar Entries
- PHP: Skipping index page call in URL (169 recent visits)
- PHP project: convert times to numbers (326 recent visits)
- PHP – passing variables across pages (9470 recent visits)
- Install Apache, PHP, MySQL on Windows (185 recent visits)
- Code mnemonics: PHP implode/explode (419 recent visits)
- Swap banner image with CSS and PHP (692 recent visits)
Stats
677 unique visits since August 2008
Recent Referrers (click)
- php function optional parameter
- optional parameter php
- if php parameter click
- PHP parameters
- getting parameter using php
- optional dans PHP
- php function optional variable
- php function optional variable
- php optional parameter
- setting up optional arguments in php functions
- call function with optional parameters php
- php optional parameters
- php optional function arguments
- php functional optional parameters
- parameter in php function
- php function optional inputs
- function with optional inputs +php
- php function parameter
- php optional function parameter
- http://search1.incredimail.com