I am trying to dynamically create a database to generalize the database entity for the project I'm working on. I basically want to dynamically create a set of standard methods and tools for properties in any class that extends this. Very similar to the tools you get for free with Python / Django.
I got an idea from this guy: http://www.stubbles.org/archives/65-Extending-objects-with-new-methods-at-runtime.html
So, I implemented the __call function as described above,
public function __call($method, $args) { echo "<br>Calling ".$method; if (isset($this->$method) === true) { $func = $this->$method; $func(); } }
I have a function that gives me public / protected properties through get_object_vars,
public function getJsonData() { $var = get_object_vars($this); foreach($var as &$value) { if (is_object($value) && method_exists($value, 'getJsonData')) { $value = $value->getJsonData; } } return $var; }
and now I want to create several methods for them:
public function __construct() { foreach($this->getJsonData() as $name => $value) { // Create standard getter $methodName = "get".$name; $me = $this; $this->$methodName = function() use ($me, $methodName, $name) { echo "<br>".$methodName." is called"; return $me->$name; }; } }
Thanks to Louis H., who pointed to the "use" keyword for this below. This basically creates an anonymous function on the fly. The function is called, but it is no longer in the context of this object. It creates a "Fatal Error: Unable to Access Protected Property"
Unfortunately, I am associated with PHP version 5.3, which excludes Closure :: bind. Therefore, the proposed solution in Lazy methods of the loading class in PHP does not work.
I'm pretty much worried here ... Any other suggestions?
Refresh
Edited for brevity.