Our blog

 

PHP, __get() and empty() Not Working As You Expect? – Solution

If you are tearing your hair out trying to figure out why empty($object->property) = true when var_dump($object->property) outputs a value - this might be the problem.

It arises if you are using the magic __get() method to serve up object properties.

Apparently PHP's empty() function actually uses isset() to determine if the property is empty or not. To get this to work properly, you also need to declare a magic __isset() method.

This is how I got around this problem:

PHP:
  1. public function __get($key){
  2.     if(/* some condition to return your key */){
  3.         return $this->$key;
  4.     }
  5.     return null;
  6. }
  7.  
  8. public function __isset($key){
  9.     if(null===$this->__get($key)){
  10.         return false;
  11.     }
  12.     return true;
  13. }

thanks to Janci's comment here, I'm not sure how long that would have taken me to figure out on my own, but for sure you saved me a LOT of time. I hope this blog post helps out someone else who hits this same issue.

More Reading:

One Comments

noisebleed
December 26th, 2010

Man, thanks thanks thanks! I've lost some hours with this 'mystery'. This post is a life saver ;)

 

 

Leave a Reply