Extending PHP5.3 objects at runtime with lambda functions
1v$ Mon Jan 5 23:58:44 GMT 2009
"PHP 5.3":http://snaps.php.net/ will include "lambda functions and closures":http://wiki.php.net/rfc/closures.
One interesting thing that will come from this will be the ability to dynamically add a method onto a class at runtime, by combining lambas with the magic __call method..well, at least a hack to make something like this.
Effectively this is similar to "traits/grafts":http://wiki.php.net/rfc/horizontalreuse, except you don’t have to define anything in a new class, you just extend the object itself when you come to use it.
You could also use a singleton within the Extensible class that keeps track of any added methods and propagates them to any other existing or new instances.
<?php class Extensible { var $_methods=array(); function __call($name, $args) { if (array_key_exists($this->_methods, $name)) { call_user_func_array(array($this, $name), $args); } else { throw new Exception(‘Unknown dynamic method ‘ . $name . ‘ called in class ‘ . get_class($this)); } } function __set($name, $value) { if (is_callable($value)) { $this->_methods[$name] = $value; } } } class MyClass extends Extensible { function test() { echo ‘Non-dynamic method’; } } $object = new MyClass(); $object->test2 = function () { echo ‘Dynamic method’; }; // test() is defined within the static class definition $object->test(); // test2() was created dynamically at runtime, but you call it just as // if it had been in the class definition $object->test2(); ?>
EDIT:
Incidentally this my first proper post sent via email. w00t.