Check if any property in a object is empty

Mathias Hillmann

I have the following function in a class:

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?");
        }
    }

However I would like to check if any property in the $this object is empty in a dynamic way, without using an If, considering this will have more properties later.

u_mulder

You can iterate over $this and throw your exception on first empty property found:

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?");
        }
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related