首页 > 解决方案 > 返回时的 php 类型声明联合(对象或布尔值)

问题描述

我正在编写带有返回值类型声明的代码(php 7.3)。当我只返回一种类型时,这不是问题(如下例所示,DoSomething1将返回 的对象SomeOtherClass)。虽然我经常发现需要进行验证并false在操作失败时返回 a 。我知道我不能在退货时进行联合(根据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();
  }
}

标签: phptype-declaration

解决方案


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

是否可以输入不止一种类型的提示?

精简版:

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

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

class SomeClass {
  function DoSomething2 (array $withMe) : ?SomeOtherClass { // note the ?
    if (/* some validation code that will return false */) 
      return null;   // not false but null
    return new SomeOtherClass();
  }
}

推荐阅读