Call functions created at runtime

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.

+4
source share
2 answers

Instead of updating the original question above, I am including a complete solution here for those struggling with the same problems:

First of all, since closure cannot have access to the real object, I had to include the actual value with the "use" declaration when creating the closure function (see the previous __construct function):

 $value =& $this->$name; $this->$methodName = function() use ($me, $methodName, &$value) { return $value; }; 

Secondly, the __call magic method simply did not require a call to the close function, it also needed to return any result. So instead of just calling $ func (), I return $ func ();

This is a trick !:-)

0
source

Try this (you have to make the variables you need for the method)

 $this->$methodName = function() use ($this, $methodName, $name){ echo "<br>".$methodName." is called"; return $this->$$name; }; 

You must have access to the context of the object through $this .

+3
source

All Articles