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

时间:2014-06-19 22:17:07

标签: php object

我需要检查一个对象是否为空或者是否有PHP中的值,并且经过研究我得到了这段代码:

$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));
}

但即使$user是一个空对象,addClient()也不会执行,因为条件不能正常工作。可以给我一些建议吗?

编辑:测试1

我使用此代码进行了一些测试:

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

结果是:     计数:     对象: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

这样告诉我用户reynierperez-mira已经存在,所以我不应该输入条件,因为我不会添加任何用户,但如果用户不存在,那么我就会这样做通过输入条件来添加。这种情况的正确条件是什么?

测试2:用户不存在

好的,我删除了所有用户,因此findClientByLogin()返回一个空对象。我以这种方式测试:

$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();

这就是输出:

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

object(stdClass)[78]

所以我把条件改为:

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

现在它有效!

1 个答案:

答案 0 :(得分:2)

您应该使用OR,而不是AND来组合条件。 count()永远不会少于0;如果对象没有属性,则计数将为0

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