I notice that in some PHP built in functions such as str_replace there are optional input variables. Can I have have optional input variables in my own functions? If so, how?
Thanks, Brian
I notice that in some PHP built in functions such as str_replace there are optional input variables. Can I have have optional input variables in my own functions? If so, how?
Thanks, Brian
The first way is to use default values for some arguments:
function doStuff($required, $optional = '', $optional2 = '') {
...
}
Now you just include a default value and then someone can do:
doStuff('foo');
doStuff('foo', 1);
doStuff('foo', 2, 3);
You need to choose an appropriate default value if the field isn't specified or to indicate that no value was set. Typical examples are ''
, 0
, false
, null
or array()
.
Or you don't need to specify them at all with func_get_args()
:
function doStuff() {
print_r(func_get_args());
}
func_get_args()
can be used with explicit arguments (the first example) as well.