I do not like functions like “getProperty” and “setProperty”, so I looked into the __get and __set functions.
I created a structure that works quite well. Now I want to use it in most of my classes. How do I do this (keeping in mind I might want to extend a class with another class) without having to duplicate code?
I already know an interface is not an option, as that’s all about duplicating code (if I understand it correctly)
Here are the functions, just in case:
/**
* Simply return the property
*/
private function __get($strProperty) {
if(array_key_exists($strProperty, $this->properties)){
$c = $this->properties[$strProperty];
// Fetch the wanted data and store it in memory
if(!$c['fetched']){
if($c['type'] == 'array'){
$proptr = $this->md->fetch_array('SELECT ' . $c['field'] . ' FROM ' . $c['table'] . ' WHERE ' . $c['where'], $c['table'].$c['field'].$c['where'], 1000);
$c['value'] = $proptr;
}else {
$proptr = $this->md->query_first('SELECT ' . $c['field'] . ' FROM ' . $c['table'] . ' WHERE ' . $c['where'], $c['table'].$c['field'].$c['where'], 1000);
$c['value'] = $proptr[$c['field']];
}
}
return $c['value'];
} else {
return $this->$strProperty;
}
}
/**
* Set the property, and update the database when needed
*/
private function __set($strProperty, $varValue) {
// If the property is defined in the $properties array, do something special
if (array_key_exists($strProperty, $this->properties)) {
// Get the fieldname
$field = $this->properties[$strProperty]['field'];
$data[$field] = $varValue;
$this->md->update(TABLE_USER, $data, $this->properties[$strProperty]['where']);
// And store the value here, too
$this->$strProperty = $varValue;
} else {
$this->$strProperty = $varValue;
}
}
If I understand you correctly you would like to automate the handing of the property array within a set of objects, if so then this should work accordingly:
This is just a basic concept but I have just tested and work’s fine, you simple extend your root classes like so:
and then use as you would normally set values using get and set magic methods, setting the methods to protected will allow the visibility of the methods to be available in all child classes but will not be allowed outside the object.
Is this what you was looking for?