« Fixed textitle usage in atom feed Dynamic PHP requires/includes, APC and Habari »

Extending PHP5.3 objects at runtime with lambda functions

1v$ date
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
Feed for this Entry

0 Responses to Extending PHP5.3 objects at runtime with lambda functions

    There are currently no comments.

About You

Email address is not published

Add to the Discussion


Subscribe to Feed

Navigation

Asides

  • January 9 - Fixed textitle usage in atom feed

    I’ve started using Textile) for markup in my posts, but it wasn’t getting parsed in my Atom feed..now fixed!

  • January 2 - No xmlrpc to Habari from G1

    The Android Market place doesn’t have any xmlrpc apps to work with Habari, just one that should work but doesn’t as it’s doing something only Wordpress seems to understand. FAIL.

More Posts

Recent Comments

Links

Latest tweet on Twitter

User Login