【发布时间】: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();
}
}
【问题讨论】:
-
这能回答你的问题吗? stackoverflow.com/questions/37033142/…
-
尼克,是的,这实际上对我有很大帮助。也会用这些信息更新我的答案。谢谢!
标签: php type-declaration