Oi! This sounds like it's going to get complicated. Which is usually a sign that I shouldn't be doing it this way!
Perhaps if I explain what I'm trying to achieve someone can point me in the right direction.
I have a base Product class, which will be extended by, for example ShoppingCartProduct, and most likely many more.
The Product class has a lot of properties, a few core ones being name, price, description, delivery_time.
I wanted the application side not to necessarily need to deal with the explicit retrieval of product details from the database, so I wanted to smoothly let the class grab required data from the database as it needs it. What I wanted to do was, when a property is accessed, return the property if it has been set, otherwise, grab a whole bunch of fields from the database, return the one that is being accessed, but store the other fields for use in the future, so we can cut out single field database calls.
/*define fields that can be populated from the database
this way a getter can query the database if something has not been set, and store the returned result for other getters
private $dbFields = array('id', 'name', 'price', 'description', 'delivery_time', 'stock', 'vat_rate');
private $dbValues = array();
public function __get($name)
//if property has been set in the object, return it
//if, after all that, the value is available, set it in the object
//if we've got this far something's gone wrong and we've attempted to access a nonexistant property
trigger_error("Attempting to access non-existant product property ".$name);
protected function getAllFieldsFromDB()
//get all applicable db fields into an array for all the getters to access db values that haven't been set
$q = query("SELECT 'id', 'name', 'price', 'description', 'delivery_time', 'stock', 'vat_rate' FROM products WHERE id=".$this->id);
if(!$q or mysql_num_rows($q)<1) return false;
$row = mysql_fetch_assoc($q);
foreach($row as $var=>$val)
Using magic __get seemed at first like a neat way to make this work. Is it perhaps not the best or right way? Another idea was to use my constructor to dynamically create getter functions (eg getId(), getName()), and in my code just call the function. But is it even possible to dynamically create class functions? I guess I could use magic function _call()?