How to check that an object is empty in PHP?

前端 未结 11 2062
不思量自难忘°
不思量自难忘° 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: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 ) );
    

提交回复
热议问题