php - 返回时的 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();
}
}
解决方案
经过更多搜索后,我找到了自己问题的答案:
精简版:
- 这是不可能的
- 将可能在 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();
}
}
推荐阅读
- javascript - SyntaxError 的问题:位置 0 处 JSON 中的意外标记 K
- javascript - 尝试循环条件为什么我变得未定义
- sql - 使用多条件案例修改选择查询
- sharepoint-online - 如何将索引属性添加到站点所以我可以构建一个结果源来搜索所有站点以查找具有此属性的内容
- python - 在 apply 中传递关键字参数会导致无效的语法错误
- python - 心跳会话过期,标记协调器死亡
- operating-system - 关键部分问题的两个过程解决方案-算法1
- python - 限制单行中字典的大小
- c# - 如何在 UWP 中计算直线的旋转坐标
- android - 线性布局中没有按钮显示?