Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing NULL param exactly the same as passing no param

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);
like image 842
park Avatar asked Jan 01 '11 08:01

park


2 Answers

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.

like image 145
Matthew Flaschen Avatar answered Oct 05 '22 23:10

Matthew Flaschen


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

?>
like image 38
thirtydot Avatar answered Oct 06 '22 00:10

thirtydot