Hi.
The PHP array_map() function is a good one…
$lower = array('marcus', 'lastcraft');
$capitalised = array_map('uc_first', $lower);
print_r($capitalised);
Basically you blast the whole array with a function in one go, avoiding looping through it. A much more declarative style.
You can write your own call back functions, as the function name is usually passed as a string…
function process_text($callback, $text) {
$replaced = array();
foreach (split($text) as $word) {
$replaced[] = $callback($word);
}
return implode(' ', $replaced);
}
The OO equvalent is either observer, listener or visitor. The listener…
class XmlListener {
function openTag($tag, $attributes) { ... }
function characterData($text) { ... }
function closeTag($tag) { ... }
}
class XmlParser {
function parse($xml, $listener) { ... }
}
As the parser reads the text, it sends the results as calls to the listener.
The Observer pattern has a single notify() method rather than a full interface. This is equivalent of the delegate in C# I believe (someone please correct me).
The Visitor pattern involves passing the caller itself in as the listener. Say we are using the parser from an RSS reader…
class RssReader {
function read($url) {
$parser = new XmlParser();
$parser->parse(file($url), $this);
}
function openTag(...) { ... }
function characterData(...) { ... }
function closeTag(...) { ... }
}
Here it’s especially effective. All the RSS code is in one place, and you don’t need any clumsy iterators to move over the data structure (here, text tokens). The Visitor/Listener is often a very nice replacement for the Iterator pattern. It means the mechanics of iteration can stay in the data structure being traversed.
Other languages have different tricks for this. Ruby/Smalltalk/Perl can pass an anonymous block of code (PHP lambda functions are rubbish by comparison). Java can pass an anonymous inner class to avoid polluting the namespace.
For functional languages, callbacks are the foundation. It’s how you get the code to the data. You will see things like “list comprehensions” (basically generators and transformers) used in the same context. Python has some support for this, but I’m not a Python developer, so hopefully someone else will elaborate.
yours, Marcus