Assume I have a method/function with the following signature:
foo($bar = 0)
Inside foo, how do I tell if $bar was set or not? isset will alway return a TRUE since $bar is assigned 0 in the event nothing is passed to foo.
Checking for 0 is not an option. I need to know the difference between the parameter explicitly being set to 0 or defaulting to 0.
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
When creating functions in PHP it is possible to provide default parameters so that when a parameter is not passed to the function it is still available within the function with a pre-defined value. These default values can also be called optional parameters because they don't need to be passed to the function.
Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If majority of the time you are calling a function using the same values for some parameters, you should try making those parameters optional to avoid repetition.
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.
Simply use func_num_args() to specifically check for how many arguments were passed in.
<?php
function foo($bar = 0)
{
echo "\nNumber of arguments: " . func_num_args();
}
// Outputs "Number of arguments: 1"
foo(0);
// Outputs "Number of arguments: 0"
foo();
?>
Live example
You can use func_get_args
. Example:
function foo($optional=null) {
if (count(func_get_args()) > 0)
echo "optional given\n";
else
echo "optional not given\n";
}
foo(); //optional not given
foo(null); //optional given
Note that the convention used for internal PHP functions is to always give optional arguments a default value and to have them have the same behavior when both argument is not given and its default value is explicitly given. If you ever find otherwise, file a bug report. This let's you do stuff like this without if
s:
function strpos_wrap($haystack, $needle, $offset = 0) {
return strpos($haystack, $needle, $offset);
}
This convention is more enforced is userland, as the difficulty that led you to this question has shown you. If the convention doesn't suit your needs, at least reconsider your approach. The purpose of func_num_args
/func_get_args
is mainly to allow variable argument functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With