4

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Sinthia V
  • 2,103
  • 2
  • 18
  • 36

2 Answers2

6

There is a magic method called __isset() that works similarly to __get() and __set(). It will let you call isset on your dynamic properties

hair raisin
  • 2,618
  • 15
  • 13
  • So do I undersand correctly, you do have to define the functionality for the method yourself, but you call it __isset()? Does it get called automatically when isset() can't find the property? – Sinthia V Oct 23 '11 at 03:17
  • Correct. You would put code in the __isset to check your dynamic property – hair raisin Oct 23 '11 at 03:22
3

__isset() is triggered by calling isset() or empty() on inaccessible properties.

You can define __isset() magic method to do it. See here.

xdazz
  • 158,678
  • 38
  • 247
  • 274