Freek van Der Herten: When empty is not empty
As PHP developers, dealing with the "helpful" automatic type shifting the language performs can sometimes be challenging. It can lead to some interesting situations like the one Freek van Der Herten has posted about where something that seems "empty" actually isn't.
Recently when I was working on a project I got some strange results when using the empty function. That's really odd [that the result was a string and "empty" when a value was set]. How can a variable hold a string and be empty at the same time?
He includes a few other tests on the same object and
firstName property using other "empty" checks with isset and is_null. Those behaved as expected so he started to look more into the class the object is based on. In the class values/properties are returned via magic methods, not direct functions. In the case of
empty, this fetching isn't interpreted prior to the check and the result appears "empty". To fix the issue, he recommends implementing an
__isset magic method that will then get called to ensure the value is actually set before fetching it.