Skips NULL param just like skipping a parameter

I am 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 of $p5 , but for approval I still want to pass something like NULL . So my question is, does PHP handle NULL passing in the same way that it doesnโ€™t miss anything?

 somefunc($p1, $p2, $p3, $p4 = SOM_CONST); somefunc($p1, $p2, $p3, $p4 = SOM_CONST, NULL); 
+7
function parameter-passing php parameters optional-parameters
source share
4 answers

Not. The exact signature is supposedly:

 function afunc($p1, $p2, $p3, $p4 = SOM_CONST) 

and for $p5 function uses func_get_arg or func_get_args .

func_num_args will differ depending on whether you pass NULL. If we do this:

 { echo func_num_args(); } 

then

 afunc(1,2,3,4,NULL); 

and

 afunc(1,2,3,4); 

give 5 and 4.

It depends on whether you need to process the same ones.

+9
source share

Not. This is the same if the default value of the parameter is NULL , otherwise:

 function a($a, $b, $c = 42) { var_dump($c); } a(1, 2, NULL); 

prints NULL .

So you cannot say that it is always the same. NULL is just another value, and it is not that important.


Not to mention the optional parameters: Calling a(1) will give you an error message (warning), but a(1,NULL) works.

+7
source share

Passing NULL exactly the same as not passing the argument - if the default value is NULL , except in the context of func_num_args :

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 ?> 
+5
source share

First of all, your function signature is incorrect. In PHP, it is strongly recommended that you save optional parameters after all optional parameters.

At this point, if you need to skip some optional parameters, you can specify NULL as their values, and the function will use their default value. It will be like using the Elvis operator in $x = $x?? 12 $x = $x?? 12 $x = $x?? 12 $x = $x?? 12 This code will set $ x to 12 only if $ x === NULL.

Using the number of arguments with the func_num_args () function should not even be mentioned here, because regardless of the value of the argument, if you pass an argument in a function call, this argument will be noticed by the function. And when it comes to the inner workings of a function, the optional NULL argument is just as good as any other value. Your code may need an argument to be VALID for some task.

The only special handling occurs when an optional function parameter is populated with a NULL argument.

+1
source share

All Articles