How to check that an object is empty in PHP?

前端 未结 11 1995
不思量自难忘°
不思量自难忘° 2020-11-29 03:31

How to find if an object is empty or not in PHP.

Following is the code in which $obj is holding XML data. How can I check if it\'s empty or not?

相关标签:
11条回答
  • 2020-11-29 04:20

    You can cast to an array and then check if it is empty or not

    $arr = (array)$obj;
    if (!$arr) {
        // do stuff
    }
    
    0 讨论(0)
  • 2020-11-29 04:25

    Using empty() won't work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared.

    Therefore you can use count() (if the object is Countable).

    Or by using get_object_vars(), e.g.

    get_object_vars($obj) ? TRUE : FALSE;
    
    0 讨论(0)
  • 2020-11-29 04:26

    If you cast anything in PHP as a (bool), it will tell you right away if the item is an object, primitive type or null. Use the following code:

    $obj = simplexml_load_file($url);
    
    if (!(bool)$obj) {
        print "This variable is null, 0 or empty";
    } else {
        print "Variable is an object or a primitive type!";
    }
    
    0 讨论(0)
  • 2020-11-29 04:28

    If an object is "empty" or not is a matter of definition, and because it depends on the nature of the object the class represents, it is for the class to define.

    PHP itself regards every instance of a class as not empty.

    class Test { }
    $t = new Test();
    var_dump(empty($t));
    
    // results in bool(false)
    

    There cannot be a generic definition for an "empty" object. You might argue in the above example the result of empty() should be true, because the object does not represent any content. But how is PHP to know? Some objects are never meant to represent content (think factories for instance), others always represent a meaningful value (think new DateTime()).

    In short, you will have to come up with your own criteria for a specific object, and test them accordingly, either from outside the object or from a self-written isEmpty() method in the object.

    0 讨论(0)
  • 2020-11-29 04:34

    Another possible solution which doesn't need casting to array:

    // test setup
    class X { private $p = 1; } // private fields only => empty
    $obj = new X;
    // $obj->x = 1;
    
    
    // test wrapped into a function
    function object_empty( $obj ){
      foreach( $obj as $x ) return false;
      return true;
    }
    
    
    // inline test
    $object_empty = true;
    foreach( $obj as $object_empty ){ // value ignored ... 
      $object_empty = false; // ... because we set it false
      break;
    }
    
    
    // test    
    var_dump( $object_empty, object_empty( $obj ) );
    
    0 讨论(0)
提交回复
热议问题