php - 检查对象中的任何属性是否为空
问题描述
我在一个类中有以下功能:
public function __construct()
{
$this->api_url = env('SUPRE_API');
$this->token = env('SUPRE_TOKEN');
if($this->api_url == null || $this->token == null){
throw new \Exception("Could not gather the Token or URL from the .env file. Are you sure it has been set?");
}
}
但是,我想以动态方式检查 $this 对象中的任何属性是否为空,而不使用 If,考虑到稍后会有更多属性。
解决方案
您可以迭代$this
并在找到的第一个空属性上抛出异常:
public function __construct()
{
$this->api_url = env('SUPRE_API');
$this->token = env('SUPRE_TOKEN');
foreach ($this as $key => $value) {
if ($value == null) {
throw new \Exception("Could not find {$key} value. Are you sure it has been set?");
}
}
}
推荐阅读
- java - JDBC 模板更新方法内部行为
- javascript - 在角度项目中编辑单个表单数据字段
- python - Tkinter 类函数在尝试使用入口小部件时导致错误
- javascript - 路由端点未路由,出现引用错误
- node.js - 在 EJS 中渲染多个项目
- xml - 使用 xpath wso2 删除外部标签
- python - 在 on_ready() 中查找公会 ID - Discord.py
- mysql - 如何使用 Ruby mysql2 插入 NULL?
- linux - rm: 无法删除 'test/deployment/sandbox-v2/tmp/dns': 权限被拒绝
- r - R中的多个绘图在一个页面中