class M
{
function double($a) {
return $a * 2;
}
}
$m = new M;
$list = array(1, 2, 3);
$list = array_map(array($m, 'double'), $list);
print_r($list);
Array
(
[0] => 2
[1] => 4
[2] => 6
)
Showing posts with label php. Show all posts
Showing posts with label php. Show all posts
Friday, December 5, 2008
PHP: Invoking a method with Map
Ever since I learned the basics of functional programming, I've been a fan of the map function. In the right context, it can be an elegant solution for array transformation. Of course, like anything, it can be misused. Using PHP's map, it's non-obvious how to make it invoke an instance method rather than a function. The following example illustrates how this can be accomplished.
Tuesday, March 18, 2008
PHP Test Trick
This is a trick that works in a lot of languages. Say you have a file containing a library that also has some utility in it's own right. As an example, I wrote a metadata parser at Grooveshark called MetaShark. It's basically a file containing a bunch of "utility functions" that are invoked via a call to main() inside of the file. It came time to write a unit test for the parser, but I didn't want to call main() from inside of the test suite because that would have the unwanted side effect of processing the current batch of jobs. Instead I want to test the methods individually and make MetaShark just work as a library. All you have to do to make this work is something simple like this:
if ($argv[0] == basename(__FILE__)) {
main();
}
or in Ruby:
if __FILE__ == $0
main()
end
Extrapolate to your language of choice.
if ($argv[0] == basename(__FILE__)) {
main();
}
or in Ruby:
if __FILE__ == $0
main()
end
Extrapolate to your language of choice.
Subscribe to:
Posts (Atom)