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.
May 2nd, 2008 at 2:37am
Why would you use array_walk and create that nasty inline function? Why not just foreach and prepend?
$sURL = 'http://twofishcreative.com';
$aResources = array('one', 'two', 'three');
foreach ($aResources as ?
$sFile = $sURL . $sFile;
print_r($aResources);
Or if you really wanted to do it the ugly way and use array_walk, don't write the function inline.
May 2nd, 2008 at 4:13pm
I was thinking in Ruby, and it doesn't translate, because PHP doesn't have a nice way to create the equivalent of a Ruby block. The point is that create_function is really ugly and horrible.
I want the _very simple_ processing code to be right there, not in a separate function. Yes, foreach is fine for this particular issue, but there are other times when I'd like to be able to have an anonymous function/block/Proc/whatever.