检查对象是否为空或具有值

问题描述:

I need to check if a object is empty or has values in PHP and after a research I come with this code:

$user = $this->client->findClientByLogin(array("login" => $user_data[0]->username));

if (!is_object($user) && (count(get_object_vars($user)) < 0)) {
    $this->client->addClient(array("login" => $user_data[0]->username, "password" => $password));
}

But even if $user is a empty object the addClient() is not executed since the condition doesn't work right. Can any give me some advice on this?

Edit: Test1

I did some testing using this code:

echo "Count ".count(get_object_vars($user));
echo "Is object ".!is_object($user);
var_dump($user);
die();

And the result was: Count: Is Object: 1

object(stdClass)[78]
  public 'clientsshared' => 
    object(stdClass)[160]
      public 'id_client' => int 44
      public 'login' => string 'reynierperez-mira' (length=17)
      public 'password' => string '' (length=0)
      public 'web_password' => string '09bb0def8de1262ac9e5a9b8a5935771' (length=32)
      public 'type' => int 8389121
      public 'id_tariff' => int 2
      public 'account_state' => string '0.0000' (length=6)
      public 'tech_prefix' => string '' (length=0)
      public 'id_reseller' => int -1
      public 'type2' => int 0
      public 'type3' => int 0
      public 'id_intrastate_tariff' => int -1
      public 'id_currency' => int 1
      public 'codecs' => int 19
      public 'primary_codec' => int 2
      public 'free_seconds' => string '' (length=0)
      public 'id_tariff_vod' => int 0
      public 'video_codecs' => int 0
      public 'video_primary_codec' => int 0
      public 'fax_codecs' => int 0
      public 'fax_primary_codec' => int 0
      public 'id_cli_map' => int 0
      public 'id_dial_plan' => int 1
      public 'id_dial_plan_map' => int 1
      public 'id_pbx_company' => int 0

So that tell me that the user reynierperez-mira already exists so I should not enter on conditional since I'll not add any user, but if user doesn't exists then I'll add by entering on the conditional. What is the right conditional on this case?

Test2: user doesn't exists

Ok, I delete all users so findClientByLogin() return a empty object. I test in this way:

$user = $this->client->findClientByLogin(array("login" => $user_data[0]->username));

echo "Count " . count(get_object_vars($user));
echo "Is object " . is_object($user);
echo "-----------";
var_dump($user);
die();

And this was the output:

Count 0
Is object 1
-----------

object(stdClass)[78]

So I changed the condition to:

if (is_object($user) && (count(get_object_vars($user)) === 0)) { ...

And now it works!

You should be using OR, not AND to combine the conditions. And count() can never return less than 0; if the object has no properties, the count will be 0.

if(!is_object($user) || count(get_object_vars($user)) == 0) {
    $this->client->addClient(array("login" => $user_data[0]->username, "password" => $password));
}