I was doing some research but wasn't able to find an answer (probably beacause I did not searched it right)
Consider this piece of code:
public function foo(?array $optionalParam);
And then this one:
public function foo(array $optionalParam = null);
What differs between them? Using PHPstorm I noticed that when I use the ?
, it creates a PHPdoc and mark the variable type as type|null
. But when I call the function without that argument, PHP screams on my face "you kidding me? where is $optionalParam". In the other side, I managed to use with no problems the =null
option.
Sorry if this question is too simple, but i did not find any answers online.
First of all, the ?
goes before the type, not after... other than this:
Using
public function foo(?array $optionalParam);
you are forced to pass something, that can be either null
or an array
, infact:
<?php
function foo(?array $optionalParam){
echo "test";
}
foo(); // doesn't work
foo(null); // works
foo([]); // works
where instead using
public function foo(array $optionalParam = null);
will accept null
, an array
, or 0 parameters
<?php
function foo(array $optionalParam = null){
echo "test";
}
foo(null); // works
foo(); // work
foo([]); // works
It's a PHP 7.1 feature called Nullable Types
Both of the lines you wrote are identical.
array ?$optionalParam : either an array or null
array $optionalParam = null : either an array or null
Tho using ?
you'd still need to add the parameter when calling the function.
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