Reputation: 4705
I'm writing a lightweight ORM that can map database columns to instance fields with different names
eg.
Database
Object
To do this my original design was something like this
abstract class DbObj {
/* In a subclass the author would provide the mapping of fileds
* from the database to the object
* e.g.
* array('userid' => 'user_id', 'username' => 'username'....
*/
protected static $db_to_obj = array();
/* This would be auto popuplated from $db_to_obj in reverse */
protected static $obj_to_db = array();
/* Many Methods truncated... */
/* Used by magic methods to make sure a field is legit */
public function isValidField($name) {
return in_array(strtolower($name), self::$db_to_obj);
}
}
Then I subclass this out
class Cat extends DbObj {
protected static $db_to_obj = array(
'catsname' => 'name',
'itsage' => 'age'
);
}
The isValidField
method does not work as expected. Using a debugger or a good ol fashioned var_dump
you will find that the value of self::$db_to_obj
is that of the parent class. I would understand this if isValidField
was static
, but it is not. It does have a $this
pointer and it does know its class.
Is there a workaround for this behaviour or a better architecture to use?
Upvotes: 0
Views: 100
Reputation: 11998
Don't create variables which are protected and static at the same time when using inheritance.
And if you use inheritance, you can/should do something like:
parent::isValidField($name) {
// code here
}
Upvotes: 1
Reputation: 6922
Here's a solution:
public function isValidField($name) {
$class = get_class($this);
return in_array(strtolower($name), $class::$db_to_obj);
}
Upvotes: 1