How to check if the object is empty?

How to check if a PHP object is empty (i.e. has no properties)? The built-in empty() does not work on objects in the document:

 5.0.0 Objects with no properties are no longer considered empty. 
+7
source share
4 answers

ReflectionClass :: GetProperties

http://www.php.net/manual/en/reflectionclass.getproperties.php

 class A { public $p1 = 1; protected $p2 = 2; private $p3 = 3; } $a = new A(); $a->newProp = '1'; $ref = new ReflectionClass($a); $props = $ref->getProperties(); // now you can use $props with empty echo empty($props); print_r($props); /* output: Array ( [0] => ReflectionProperty Object ( [name] => p1 [class] => A ) [1] => ReflectionProperty Object ( [name] => p2 [class] => A ) [2] => ReflectionProperty Object ( [name] => p3 [class] => A ) ) */ 

Note that newProp not returned in the list.

get_object_vars

http://php.net/manual/en/function.get-object-vars.php

Using get_object_vars will return newProp , but the protected and private members will not be returned.


Thus, depending on your needs, a combination of reflection and get_object_vars can be guaranteed.

+7
source

Here is the solution :;

 $reflect = new ReflectionClass($theclass); $properties = $reflect->getProperties(); if(empty($properties)) { //Empty Object } 
+5
source

Can you clarify this with some code? I don’t understand what you are trying to accomplish.

You can call a function on an object as follows:

 public function IsEmpty() { return ($this->prop1 == null && $this->prop2 == null && $this->prop3 == null); } 
+2
source

I believe (not quite sure) that you can override the isset function for objects. In the class, you can provide an implementation of __isset() and return it to the appropriate properties.

Try reading this: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

+1
source

All Articles