Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 328
IMB Avatar asked May 17 '18 19:05

IMB


People also ask

What is a mixed return type?

mixed is a pseudo type added in PHP 8 that conveys the type of the parameter/return/property can be of any type. mixed type includes all scalar types in PHP, null , all class objects, callable , and even resource . mixed is equivalent to a Union Type of: string|int|float|bool|null|array|object|callable|resource.

Can a python function have different return types?

Everything in Python is an object. So, your functions can return numeric values ( int , float , and complex values), collections and sequences of objects ( list , tuple , dictionary , or set objects), user-defined objects, classes, functions, and even modules or packages.


1 Answers

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.

like image 119
IMSoP Avatar answered Oct 14 '22 20:10

IMSoP