function some_func(string|null $some_arg)
function some_func(?string $some_arg)
function some_func(string $some_arg = null)
function some_func(?string $some_arg = null)
function some_func(string|null $some_arg)
function some_func(?string $some_arg)
function some_func(string $some_arg = null)
function some_func(?string $some_arg = null)
2
Answers
The
string|null
union type actually converts to?string
, so they are equivalent.$string = null
(regardless of preceding type definition) sets a default value and makes the$string
argument optional. This allows you to usesome_func()
without an argument, which will be interpreted assome_func(null)
.So ultimately not much, and syntax here will depend on the usage of
some_func
.Edit:
As pointed out in a now-deleted comment, this one seems fishy:
You’d think
string
and the default value ofnull
don’t play well, but this actually converts correctly toSo while odd, it is valid.
The four function definitions are different from each other in the way they specify the type of arguments the function expects to take.
1 – The first function, "function some_func(string|null $some_arg)", expects to receive an argument called "some_arg" which can be of type "string" or "null". This means that the function can be called either passing a string or passing null.
2 – The second function, "function some_func(?string $some_arg)", expects to receive an argument called "some_arg" which can be of type "string" or "null". This is the same as the first function, but using the "?" before the argument type.
3 – The third function, "function some_func(string $some_arg = null)", expects to receive an argument called "some_arg" which is of type "string", but if no arguments are passed, the default value is "null". This means that the function can be called without passing any arguments, but if an argument is passed it must be a string.
4 – The fourth function, "function some_func(?string $some_arg = null)", expects to receive an argument called "some_arg" which can be of type "string" or "null", and if no argument is passed, the default value will be " null". This means that the function can be called without passing any arguments or passing null.