skip to Main Content
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


  1. 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 use some_func() without an argument, which will be interpreted as some_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:

    function some_func(string $some_arg = null)
    

    You’d think string and the default value of null don’t play well, but this actually converts correctly to

    function some_func(?string $some_arg = null)
    

    So while odd, it is valid.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search