Declaring Optional Input Variables in PHP Functions CodeUnit 13 JAN 2009

PHPJust a simple one this time around to give you the syntax for adding optional input variables to your PHP functions. This is pretty useful if you are going back and making changes to legacy functions by introducing new functionality to them but at the same time don’t necessarily want to break any of your old code – in other words it allows you to provide for full backwards compatibility in terms of your existing function calls.

So let’s assume you used to have a function that looked like this:

function test($a,$b)
{
//do what you need
}
?>

Now you want the function to behave a little differently, so you add a new input variable to control the function’s… well function. Your function now looks a little like this:

function test($a,$b,$c)
{
if ($c == 1)
//do what you need
else
//new do what you need
}
?>

Obviously this will immediately break all of your existing code simply because the function’s signature now looks completely different! The way around it? Well, simply declare $c as an optional variable and set its default value to 1, meaning that any old calls to the function will in fact by default be calling test(a,b,1) while your new function calls can take advantage of the new switch and look something like test(a,b,2).

So how do you do this? Well, simply declare your function like this:

function test($a,$b, $c=1)
{
if ($c == 1)
//do what you need
else
//new do what you need
}
?>

And there you have it. By setting your input variable to a value, you automatically make it an optional input variable. Pretty simple, isn’t it? :)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.