I have a set of classes which hold state for the database. It’s like a micro-ORM pattern. So for this solution I load in the structure of a few tables as dynamic properties to the class so that the class looks something like:
- Object
- [tbl_name]
- attribute1
- attribute2
- attribute3
- [tbl_name]
- attribute1
- attribute2
- attribute3
- [tbl_name]
All of the attributes are public properties because I set them with something like this:
$object->{$table_name}->{$attribute} = 'foobar';
What I’d like though is for these dynamically set properties to be private. Why? Well because, and please don’t miss the irony here, I want to make them public again through an overloaded getter/setter using __get() and __set(). Again we come back to the question of why. Well actually for “getting” I would have been fine with a public property but for setting I want to apply some logic before allowing the setting. Here’s my simplified __set() function which gives you an idea of what I’m trying to achieve:
public function __set ( $property , $value ) {
if ( !in_array ($property , $blocked_properties) ) {
$this->property = $value;
$this->trigger_event ( $property );
}
}
Make sense? I’m happy to solve this problem other ways but this seems like a very graceful way to do this if only I could dynamically set private instance variables.
Don’t make those actual properties, store them in a
privatearray and access them only through magic methods:It behaves exactly how you want it.