返回时的 php 类型声明联合对象或布尔值

问题描述

我正在编写带有返回值类型声明的代码 (PHP 7.3)。当我只返回一种类型时,这不是问题(如下例所示,DoSomething1 将返回 SomeOtherClass 的对象)。尽管我经常发现需要进行验证并在操作失败时返回 false。我知道我不能在返回时执行 union(根据 DoSomething2),但是有没有解决这个问题的好方法

class SomeClass {

  // Works
  function DoSomething1 (array $withMe) : SomeOtherClass {
    return new SomeOtherClass();
  }

  // Problem,would like to return OR a SomeOtherClass OR a bool
  function DoSomething2 (array $withMe) : SomeOtherClass|bool {
    if (/* some validation code that will return false */)
      return false;  
    return new SomeOtherClass();
  }
}

解决方法

经过更多搜索,我找到了我自己问题的答案:

Is it possible to type hint more than one type?

简短版本:

  • 这是不可能的
  • 在 php8 中可以实现
  • 文档中的@return 将支持联合类型

正如@Nick 指出的那样,这是一个非常优雅的解决方法,对我有用:

http://localhost:8000/