PHP 5.3 closures

I just recently finished a project where they were using the abbrfilter. When I set up my local copy I found that it just wouldn't work at all.

After some investigation I found that the problem was since I was running on PHP 5.2 and abbrfilter was using PHP closures. Like most people we have all used closures in javascript, and they create small one off function much easier and much more elegant to code.

an example of a closure is like this.

$types = node_type_get_names();
$node_types = array_map(function ($a) use ($types) {
  return $types[$a->type];
}, $nodes);

which is really nice, and simple. Where as what we needed to do in the past was as follows.

$types = node_type_get_names();
_filter($types, TRUE);
$node_types = array_map('_filter', $nodes);
function _filter($a, $init = FALSE) {
  static $types = NULL;
  if ($init) {
    $types = $a;
  return $types[$a->type];

which is not nice at all. There are a couple of other things that also changes, and that is instead of using function_exists() to see if you can call a hook you now need to us is_callable() which will check both closures and functions.

You can see this change in Drupal 7.x which has had the basic change to underlying structures.

$hooks = array('function_name' => array($args));


$hooks = array(array('function_name', array($args)));

This means that instead of having to always use a proper function you can do the following.

$hooks = array(array(function ($args) {
  return $args['name'];
}, array($args));

which is way cool.

There is a downside to closures, and that is they are only available for use with PHP 5.3 and above. But Drupal does allow for this, since Drupal has been around for over 10 years, we had to transition through the change from 4.x to 5.x and this has allowed for when the .info files were introduced into Drupal.

So if you are going to use closure, the the following line to your info file.

php = 5.3

This will mean that your module will not enable for any system with a php version less than 5.3

Update: I have submitted commented on a related issue with abbrfilter requiring the php = 5.3 in the info so in future it will not install on PHP 5.2 system.