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

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

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:

public function __get($key){
	if(/* some condition to return your key */){
		return $this->$key;
	}
	return null;
}

public function __isset($key){
	if(null===$this->__get($key)){
		return false;
	}
	return true;
}

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.


Tags: phpobjectemptypropertymagicmethod__get__isset