IMB
IMB

Reputation: 15929

What type hint to use if return value is mixed?

function foo ($a): mixed
{
    if ($a == 1)    
        return true;
    else
        return 'foo';
}

var_dump(foo(1));

Since mixed is not a real type this results to:

Fatal error: Uncaught TypeError: Return value of foo() must be an instance of mixed...

Is there a way to type hint a mixed return value or do you simply not declare type hints in this type of scenario?

Upvotes: 18

Views: 12497

Answers (1)

IMSoP
IMSoP

Reputation: 98005

Type hints are there to enforce some restriction on the value passed or returned. Since "mixed" would allow any value at all, its use as a type hint would be pointless, so just omit it.

From PHP 8.0 onwards, you can specify "union types", which would allow you to declare the return type in your example as bool|string. (There is also a special case for including false in the union, as in false|string, since it's commonly used to indicate failure, but not for true.)

As an alternative to false|string you can use nullable type hints, which are available from PHP 7.1 onwards. , and can be specified as ?string if you want to return null on a failure instead of false.

In older versions, you can document the return value of your function, in a docblock. IDEs and documentation generators will generally understand the syntax @return bool|string. Even if you are using PHP 8, you might want to use this to add a description of why the return type varies, and when to expect which type.

Of course, an option well worth considering is to reconsider your design, and come up with a function which can communicate its result without returning different types for different cases. For instance, using exceptions instead of a special value for errors, or splitting a function like getThing(boolean $asString): float|string into two functions getThingAsFloat(): float and getThingAsString(): string.

Upvotes: 24

Related Questions