首页 > 解决方案 > 检查对象中的任何属性是否为空

问题描述

我在一个类中有以下功能:

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,考虑到稍后会有更多属性。

标签: phplaravel

解决方案


您可以迭代$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?");
        }
    }
}

推荐阅读