you should use the magic methods __Set and __get. A simple example:
class Foo { //This array stores your properties private $content = array(); public function __set($key, $value) { //Perform data validation here before inserting data $this->content[$key] = $value; return $this; } public function __get($value) { //You might want to check that the data exists here return $this->$content[$value]; } }
Of course, don't use this example like this: no security whatsoever :)
EDIT: saw your comments, there might be an alternative based on reflection and decorator:
class Foo { private $content = array(); private $stdInstance; public function __construct($stdInstance) { $this->stdInstance = $stdInstance; } public function __set($key, $value) { //Reflection for the stdClass object $ref = new ReflectionClass($this->stdInstance); //Fetch the props of the object $props = $ref->getProperties(); if (in_array($key, $props)) { $this->stdInstance->$key = $value; } else { $this->content[$key] = $value; } return $this; } public function __get($value) { //Search first your array as it is faster than using reflection if (array_key_exists($value, $this->content)) { return $this->content[$value]; } else { $ref = new ReflectionClass($this->stdInstance); //Fetch the props of the object $props = $ref->getProperties(); if (in_array($value, $props)) { return $this->stdInstance->$value; } else { throw new \Exception('No prop in here...'); } } } }
PS: I have not tested my code, just a general idea ...
Benjamin Dubois Jul 23 '12 at 18:37 2012-07-23 18:37
source share