I'm working with a function whose signature looks like this
afunc(string $p1, mixed $p2, array $p3 [, int $p4 = SOM_CONST [, string $p5 ]] )
In some cases I don't have data for the last parameter $p5
to pass, but for the sake of consistency I still want to pass something like NULL
. So my question, does PHP treat passing a NULL exactly the same as not passing anything?
somefunc($p1, $p2, $p3, $p4 = SOM_CONST);
somefunc($p1, $p2, $p3, $p4 = SOM_CONST, NULL);
No. Presumably, the exact signature is:
function afunc($p1, $p2, $p3, $p4 = SOM_CONST)
and the function uses func_get_arg
or func_get_args
for $p5
.
func_num_args
will be different depending whether you pass NULL. If we do:
{
echo func_num_args();
}
then
afunc(1,2,3,4,NULL);
and
afunc(1,2,3,4);
give 5 and 4.
It's up to the function whether to handle these the same.
Passing NULL
is exactly the same as not passing an argument - if the default value is NULL
, except in the context of the func_num_args
function:
Returns the number of arguments passed to the function.
<?php
function test($test=NULL) {
echo func_num_args();
}
test(); //outputs: 0
test(NULL); //outputs: 1
?>
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