Page 1 of 1
Passing Optional Arguments
Posted: Fri Nov 10, 2006 12:57 pm
by snowrhythm
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.
Posted: Fri Nov 10, 2006 1:07 pm
by Luke
Assign false to it and then give it a default in your function
Code: Select all
function this_has_optional_params($required, $optional=false){
if(!$optional) $optional = 'default_value';
// Do stuff
}
OR just give it the default right away
Code: Select all
function this_has_optional_params($required, $optional='default_value'){
// Do stuff
}
Posted: Fri Nov 10, 2006 1:08 pm
by John Cartwright
Code: Select all
function foobar($optional = '')
{
return var_dump($option);
}
echo foobar() .'<br />';
echo foobar('hi');

Posted: Fri Nov 10, 2006 2:18 pm
by snowrhythm
Thanks guys...I appreciate the help.
Posted: Fri Nov 10, 2006 2:33 pm
by RobertGonzalez
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
}
?>