PHP5 empty object check

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
ed209
Forum Contributor
Posts: 153
Joined: Thu May 12, 2005 5:06 am
Location: UK

PHP5 empty object check

Post by ed209 »

As of PHP 5, objects with no properties are no longer considered empty.

So,

Code: Select all

if ( !empty( $myObject ) ) {
     // object not empty
}
will not work - even if it is empty. Is there a way around this?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

User avatar
ed209
Forum Contributor
Posts: 153
Joined: Thu May 12, 2005 5:06 am
Location: UK

Post by ed209 »

so something like:

Code: Select all

if ( !count(get_object_vars( $myObject )) ) {
    // object is empty
}
I think the PHP4 method was nicer! Thanks for the reply.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I'm actually not sure how it plays with protected and private properties, so you may have to test that. Better yet, let us know of the results.

If all else fails, theres always Reflection.
User avatar
ed209
Forum Contributor
Posts: 153
Joined: Thu May 12, 2005 5:06 am
Location: UK

Post by ed209 »

I'm afraid you lost me :oops:

The above does work for what I need though, thanks. My object is pretty simple, just a load of $_POSTed values put into an object.
Post Reply