是否可以在PHP 7上指定多个返回类型? [英] Is it possible to specify multiple return types on PHP 7?

查看:1418
本文介绍了是否可以在PHP 7上指定多个返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些方法可以返回两种返回类型之一.我正在使用一个利用MCV的框架,因此重构这几个功能特别没有吸引力.

I have some methods that can return one of two return types. I'm using a framework utilizing MCV so refactoring these few functions in particular is not appealing.

是否可以声明返回类型,使其返回一个或另一个,并在其他任何操作上失败?

Is it possible to declare the return type returning one or the other and failing on anything else?

function test(): ?
{
    if ($this->condition === false) {
        return FailObject;
    }

    return SucceedObject;
}

推荐答案

在PHP 8之前,标准方法是使两个对象共享一个接口.示例:

Before PHP 8, the standard way is for the two objects to share an interface. Example:

interface ReturnInterface {}
class FailObject implements ReturnInterface {}
class SuccessObject implements ReturnInterface {}
function test(): ReturnInterface {}

在此示例中,ReturnInterface为空.它的存在仅支持所需的返回类型声明.

In this example, ReturnInterface is empty. Its mere presence supports the needed return type declaration.

您还可以使用基类(可能是抽象类).

You could also use a base, possibly abstract, class.

从PHP 8+开始,您也可以使用联盟类型:

As of PHP 8+, you may also use union types:

function test(): FailObject|SuccessObject {}

在我看来,对于这种用例,接口更加清晰和可扩展.例如,如果以后需要WarnObject,则只需将其定义为扩展ReturnInterface,而不用遍历所有签名并将其更新为FailObject|SuccessObject|WarnObject.

To me, for this use case, interfaces are more clear and more extensible. For example, if I later want a WarnObject I need only to define it as extending ReturnInterface -- rather than going through all signatures and updating them to FailObject|SuccessObject|WarnObject.

这篇关于是否可以在PHP 7上指定多个返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆