Just 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:
-
Working on old scripts can be quite annoying, particularly when you encounter an undocumented function and are trying to figure out firstly which inputs tha ...
-
So I updated a panel generating script to adhere to some campaign rules, meaning that certain graphing functions were no longer being generated by the PHP s ...
-
A very clever little jQuery function here that I've gone and lifted from some deep, dark domain of the Web. Essentially what it does is prevent accidenta ...
-
I found this little snippet of code floating around the Internet and despite its age, it still proves to be quite a handy little guy to have around when you ...
-
I make use of PHP's handy header function to handle simple page redirects for me, perhaps a bit of a cheap way of doing it, but one that is remarkable effec ...