I have a heirarchy of classes that get initialized from a database. I am using __get() and __set() with an array in a common Item base class to support different numbers of properties. One class derived from Item, UserProfile is used to store user data. There is a phone number table in my database with a one-to-many relationship to the user table to store multiple phone numbers for one user. If there is a mobile phone, then the UserProfile object has a mobile field. Same for home and business. If no number exists, no property exists.
The problem comes when I want to test for the existence of these properties. when I use code like
if (isset($clientData->home_phone))
{
$this->startElement('phone');
$this->writeAttribute('phone_number_type','home');
$this->writeRaw($clientData->home_phone);
$this->endElement();
}
The function always returns false. I tried using brackets to tell php to get the variable first, but I just got errors. Do I need a special attributeExists() function to simulate isset()'s functionality, or is there a more straightforward approach?
How can I test for the existence of a dynamic property without some kind of error?
There is a magic method called __isset()
that works similarly to __get()
and __set()
. It will let you call isset on your dynamic properties
__isset() is triggered by calling isset() or empty() on inaccessible properties.
You can define __isset()
magic method to do it. See here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With