January 13, 2008 5:07pm
I've been working on Habari a bit recently, so have been writing more PHP than Ruby lately. Given that Habari's code quality is pretty good, that hasn't been too terrible. However, I recently had to prepend a URL to a bunch of file paths, and was thinking in Ruby, where I would have done something like this:
url = "http://twofishcreative.com/"
resources = %w[one two three]
resources.map! { |resource| url + resource }
puts resources
The beauty of this is that it keeps the callback code with the calling code, making it easier to read. PHP doesn't have blocks, but it does have the create_function() function, which lets you create an anonymous function, so you can have your callback inline too.
$url = "http://twofishcreative.com/";
$resources = array("one", "two", "three");
array_walk($resources,
create_function('&$resource,$k,$url',
'$resource = $url.$resource;'), $url);
print_r($resources);
Ouch! That quoted function! Deity forbid you actually want to do anything complex in there. And you get a completely new scope, so you have to pass in any variables you need. And if you want to use more than one variable you need to do some horrible kludge like passing an array of variables.
I'll leave it as an exercise for the reader to work out which I prefer.