如果返回值混合使用什么类型的提示? [英] 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));
由于mixed
不是实型,因此导致:
Since mixed
is not a real type this results to:
致命错误:未捕获的TypeError:foo()的返回值必须为 混合...的实例
Fatal error: Uncaught TypeError: Return value of foo() must be an instance of mixed...
有没有一种方法可以在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?
推荐答案
在那里提供了类型提示,以强制限制传递或返回的值.由于混合"将完全允许任何值,因此将其用作类型提示将毫无意义,因此只需将其忽略即可.
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.
有人提议在语言中添加联合类型",这将允许您在示例中将返回类型声明为bool|string
,但尚未被接受.
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.
您可以做的是在文档块中的 document 函数的返回值. IDE和文档生成器通常会理解语法@return bool|string
,然后可以添加为什么的描述,返回类型会有所不同,以及何时期望使用哪种类型.
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.
当然,值得考虑的一个选项是重新考虑您的设计,并提出一个函数,该函数可以传达其结果 而无需针对不同情况返回不同的类型.例如,使用异常代替错误的特殊值,或者将像getThing(boolean $asString): float|string
这样的函数拆分为两个函数getThingAsFloat(): float
和getThingAsString(): string
.
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
.
这篇关于如果返回值混合使用什么类型的提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!