PHP OOP dynamically add class variables

ucsdmbdm
ucsdmbdm used Ask the Experts™
on
Hi,
I would like to create a class with variable number of class properties from a database.
For example:
User class{
var $firstname;
var $lastname;  
}
or it could be
User class{
var $firstname;
var $lastname;
var $age;
}
in the first case above firstname and lastname are returned by the database but in the second case 3 things are returned from the database so we dont know the properties beforehand.

Is it possible to loop through the database and create class properties from the database?




Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

You can have a magic __get method that checks from the stored data and returns the value if it exists, or null if it does not:

class A {

public function __get($name) {
        echo "Getting '$name'\n";
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
            'Undefined property via __get(): ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return null;
    }

}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial