Extending PHP5.3 objects at runtime with lambda functions
1v$ Thu Jan 1 0:00:00 GMT 1970
PHP 5.3 will include lambda functions and 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, 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.
Edit
0 Responses to Extending PHP5.3 objects at runtime with lambda functions
There are currently no comments.