I'd prefer something like this:
$image_urls = array_map(compose(papply('concat', 'illos/'), papply('lookup', 'url')),
$images);
This builds a function via composition: first lookup 'url' then prepend with 'illos/'. This function is then mapped over the array.
Unfortunately relies on a bunch of functions which PHP doesn't include. Unfortunately PHP's stdlib concentrates on incredibly-single-purpose functions for, eg. string manipulation, while ignoring general programming constructs. Also, most of the really useful parts of the language aren't available as functions, for no real reason. In any case, we can define these things ourself like this:
// Function composition
function compose($f, $g) {
return function() use ($f, $g) {
return $f(call_user_func_array($g, func_get_args()));
};
}
// String concatenation. Unfortunately we can't write "concat = papply('implode', '')"
function concat() {
return implode('', func_get_args());
}
// Array subscript. I'd prefer to do this the other way around and write an
// argument-flipping function, but that's unnecessary for this example
function lookup($x, $y) {
return $y[$x];
}
// Partial application
function papply() {
$args = func_get_args();
return function() use ($args) {
return call_user_func_array('call_user_func',
array_merge($args, func_get_args()));
};
}
Regarding lexical scope, Python has ridiculous gotchas too
http://stackoverflow.com/questions/5218895/python-nested-fun...PS: I still much prefer Python to PHP, but straw men aren't going to help ;)