Skip to content

Instantly share code, notes, and snippets.

@sbisbee
Created December 17, 2010 23:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbisbee/745878 to your computer and use it in GitHub Desktop.
Save sbisbee/745878 to your computer and use it in GitHub Desktop.
First-class functions in PHP.
<?php
/*
* A demonstration of first-class functions in PHP.
* Blog post: http://www.sbisbee.com/blog.php?id=2352301864
*
* By Sam Bisbee <www.sbisbee.com> on 2010-12-17
*/
function makeLouder($fn)
{
return function($a) use($fn) {
return $fn($a)."!!!";
};
}
$foo = makeLouder(abs);
echo "<p>".$foo(900)."<br/>".$foo(-900);
$bar = makeLouder(strtoupper);
echo "<p>".$bar("upper");
function makeDerivative($fn, $deltaX)
{
return function($x) use ($fn, $deltaX) {
return ($fn($x + $deltaX) - $fn($x)) / $deltaX;
};
}
$cos = makeDerivative(sin, 0.00000001);
echo "<p>".$cos(0); // 1
echo "<p>".$cos(pi() / 2); // 0
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment