Passing Optional Arguments
Moderator: General Moderators
- snowrhythm
- Forum Commoner
- Posts: 75
- Joined: Thu May 04, 2006 1:14 pm
- Location: North Bay Area, CA
Passing Optional Arguments
I'm sure everyone knows about functions that you can pass 'optional' arguments to, I was just wondering if there is any special syntax for creating a function myself that can work that way. That is, a function where some parameters are necessary and some are optional. Thanks.
Assign false to it and then give it a default in your function
OR just give it the default right away
Code: Select all
function this_has_optional_params($required, $optional=false){
if(!$optional) $optional = 'default_value';
// Do stuff
}Code: Select all
function this_has_optional_params($required, $optional='default_value'){
// Do stuff
}- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Code: Select all
function foobar($optional = '')
{
return var_dump($option);
}
echo foobar() .'<br />';
echo foobar('hi');- snowrhythm
- Forum Commoner
- Posts: 75
- Joined: Thu May 04, 2006 1:14 pm
- Location: North Bay Area, CA
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
For clarity you may want to default to the same type as what is expected to be passed to it.
Code: Select all
<?php
function my_function($int = 0, $str = '', $bool = false)
{
// yaddah yaddah
}
?>