phptype-declaration

PHP type hints: is it possible to have a nullable union like ?string|array ...?


I'm on PHP 8.2.1. The following type hints work fine:

function abc(): ?string
function abc(): ?array
function abc(): string|array

...but a nullable union doesn't:

function abc(): ?string|array

>>> ParseError: syntax error, unexpected token "|", expecting "{"

Is there any workaround?


Solution

  • Is there any workaround?

    the so called nullable type in PHP (since 7.1) was an early way to allow to attribute allowing null as well to a single return type to laxen the rules. it was deemed useful when PHP started with return types as only a single type was allowed to be typed and returning null as well a common scenario.

    function abc(): ?string
    
    function abc(): ?array
    

    since version 8.0 PHP has union types, that is with the pipe symbol ("|"), shown in your third definition:

    function abc(): string|array
    

    you could however likewise use union types when upgrading the earlier code to union types:

    function abc(): null|string
    
    function abc(): null|array
    

    so as workaround, perhaps the nullable type is better classified as, and then it may become more clear that the union type of all three is what you're looking for (and not a workaround, at least in my book and IIUC):

    function abc(): null|string|array
    

    the nullable type notation with the question mark symbol ("?") survives in code-bases because it is much shorter and the usage is common - but incompatible with the pipe-notation of union types.

    it may also have a bit of a renaissance with the release of PHP 8.4 as it deprecates using null as default value for a parameter given the parameters type does not include null. adding the type as an attribute to a parameter is supported since PHP version 5 for array and classes.