沃梦达 / 编程问答 / php问题 / 正文

如果返回值是混合的,使用什么类型的提示?

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:

致命错误:未捕获的类型错误: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.

从 PHP 8.0 开始,您可以指定联合类型",这将允许您将示例中的返回类型声明为 bool|string.(在联合中包含 false 也有一种特殊情况,如 false|string,因为它通常用于指示失败,但不适用于 true.)

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.)

作为 false|string 的替代方法,您可以使用 可空类型提示,从 PHP 7.1 开始提供., 如果你想在失败时返回 null 而不是 false,可以指定为 ?string.

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.

在旧版本中,您可以在文档块中记录函数的返回值.IDE 和文档生成器通常会理解语法 @return bool|string.即使您使用的是 PHP 8,您也可能希望使用它来添加为什么返回类型变化的描述,以及何时期望哪种类型.

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.

当然,一个非常值得考虑的选择是重新考虑您的设计,并提出一个可以传达其结果的函数针对不同的情况返回不同的类型.例如,使用异常而不是错误的特殊值,或者将像 getThing(boolean $asString): float|string 这样的函数拆分为两个函数 getThingAsFloat(): floatgetThingAsString(): 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.

这篇关于如果返回值是混合的,使用什么类型的提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果返回值是混合的,使用什么类型的提示?

基础教程推荐