Page 1 of 1
building functions with optional parameters
Posted: Sun Dec 18, 2005 9:41 am
by malcolmboston
im building a function atm that i would like to be able to pass an optional 2nd parameter, how could this be written without throwing a PHP error
Code: Select all
function ExampleFunction ($Mode, $Filter)
{
// only run certain code if $filter has been passed
}
obviously i could preset $filter = "NONE", and do it based that but, you can do it with standard PHP functions so i am interested in doing it this way
Re: building functions with optional parameters
Posted: Sun Dec 18, 2005 9:58 am
by onion2k
Code: Select all
function ExampleFunction ($Mode, $Filter="NONE")
{
// only run certain code if $filter has been passed
}
If $filter isn't passed then it'll default to NONE.
Posted: Sun Dec 18, 2005 10:05 am
by malcolmboston
if filter isnt passed then it will throw up a PHP error, internal PHP functions allow you to do this....am i explaining what i mean badly?
Posted: Sun Dec 18, 2005 10:22 am
by jmut
Posted: Sun Dec 18, 2005 10:27 am
by malcolmboston
Code: Select all
function ExampleFunction ($Mode, $Filter)
{
// only run certain code if $filter has been passed
}
example for call usage
i would have to do this
Code: Select all
ExampleFunction ($Mode = "MODE1", $Filter = "NONE")
Code: Select all
// i want to do this
ExampleFunction ($Mode = "MODE1);
basically assuming $filter is not passed there is not one set, however i would get an invalid arguments passed error
Posted: Sun Dec 18, 2005 10:30 am
by acidHL
Onion2k's post does what you want to do.
Posted: Sun Dec 18, 2005 10:33 am
by malcolmboston
i know that, what im saying is that i dont want to do it that way if possible, various internal PHP functions take optional arguents that are only used if you pass the parameter too them, why cant i do it and if i can, whats the syntax
Posted: Sun Dec 18, 2005 10:45 am
by onion2k
malcolmboston wrote:i know that, what im saying is that i dont want to do it that way if possible, various internal PHP functions take optional arguents that are only used if you pass the parameter too them, why cant i do it and if i can, whats the syntax
I see what you mean.
Code: Select all
function blah($a,$b=NULL) {
if (isset($b)) { echo "something"; } else { echo "nothing"; }
}
You'll still need to detect if the optional parameters are set though .. it's really no less work. PHP's internal functions are doing that too.
Posted: Sun Dec 18, 2005 10:47 am
by malcolmboston
thank you