Reputation: 299
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);
Upvotes: 9
Views: 16179
Reputation: 3389
First of all, your function signature is incorrect. It is highly recommended in PHP to keep the optional parameters after all the non optional parameters.
At that point, if you need to skip some of the optional parameters, you can provide NULL
as their values and the function will use their default value. It will be similar to using the null coalesce operator in $x = $x ?? 12
. This code will set $x
to 12
only if $x === NULL
.
Using the number of arguments with func_num_args()
should not even be mentioned here because no matter what the value of the argument is, if you pass an argument in the function call, then that argument will be noticed by the function. And when it comes to the inner workings of the function, an extra NULL
argument is just as good as any other value. Your code might need an argument to be NULL
in order to perform some task.
The only special treatment happens when an optional function parameter is filled with a NULL
argument.
Upvotes: 1
Reputation: 816700
No. It is only the same if the parameter's default value is NULL
, otherwise not:
function a($a, $b, $c = 42) {
var_dump($c);
}
a(1, 2, NULL);
prints NULL
.
So you cannot say it is always the same. NULL
is just another value and it is not that special.
Not to mention non-optional parameters: Calling a(1)
would give you an error (warning) but a(1,NULL)
works.
Upvotes: 7
Reputation: 228192
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
?>
Upvotes: 5
Reputation: 284876
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.
Upvotes: 11