Tuesday, February 05, 2013

In Pursuit of More Compact PHP Code

One day I'll have reliable access to PHP 5.3 and real anonymous functions. Alas, that day is still far off for me. Recently, however, I put together a few trivial functions to make using the old school create_function capability easier. Or, at least easier for quick one liners. I give you: fn1($code), fn2($code) and fn3($code).

A few sample uses:

$prefixed = array_map(fn1('return "x_" . strtoupper($x);'), $data); // [1]

$mathed   = array_reduce($values, fn2('return $x + sqrt($y);'), 0); // [2]

$e = $do_encoding ?                                                 // [3]
     fn1('return mb_convert_encoding($x, "Windows-1251", "UTF-8");') :
     fn1('return $x;');

$texted   = $e($a) . "//" . $e($b) . "//" . $e($c);

The third example is the most fun one, as it shows that functions can be sort-of treated as first class values.

The implementation of these functions couldn't be simpler:

function fn1($code) {
  return create_function('$x', $code);
}

function fn2($code) {
  return create_function('$x,$y', $code);
}

function fn3($code) {
  return create_function('$x,$y,$z', $code);
}

As my freshman professor, Kulbir Arora once said: Be Pithy. I'm trying man, I'm trying.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails