问题
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?
回答1:
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.
There have been proposals to add "union types" to the language, which would allow you to declare the return type in your example as bool|string, but none has yet been accepted.
What you can do is document the return value of your function, in a docblock. IDEs and documentation generators will generally understand the syntax @return bool|string, and you can then 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.
来源:https://stackoverflow.com/questions/50399112/what-type-hint-to-use-if-return-value-is-mixed