Declaring Optional Input Variables in PHP Functions

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? :)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials. Bookmark the permalink.
  • Shaffy

    Great Effort

  • http://www.craiglotter.co.za Craig Lotter

    Coolio.

blog comments powered by Disqus