Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP:isset() returns false for object's dynamic properties

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?

like image 475
Sinthia V Avatar asked Jan 19 '23 10:01

Sinthia V


2 Answers

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

like image 116
hair raisin Avatar answered Jan 31 '23 07:01

hair raisin


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

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

like image 37
xdazz Avatar answered Jan 31 '23 07:01

xdazz