【问题标题】:php type declaration union on return (object or bool)返回时的 php 类型声明联合(对象或布尔值)
【发布时间】:2021-04-11 19:56:46
【问题描述】:

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

【问题讨论】:

标签: php type-declaration


【解决方案1】:

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

Is it possible to type hint more than one type?

短版:

  • 这是不可能的
  • 在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();
  }
}

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多