Skip to content

Instantly share code, notes, and snippets.

@yhirose
Created February 2, 2012 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yhirose/1721247 to your computer and use it in GitHub Desktop.
Save yhirose/1721247 to your computer and use it in GitHub Desktop.
PHP Lambda based memoizer
<?php
// Lambda based memoizer
function memoize($fn) {
$cache = array();
return function ($key) use($fn, &$cache) {
if (!isset($cache[$key])) {
$cache[$key] = $fn($key);
}
return $cache[$key];
};
}
// Simple usage
$m = memoize(function ($key) {
return "[$key]";
});
var_dump($m('one'));
var_dump($m('two'));
var_dump($m('one'));
// Usage with class
class Test {
public function __construct() {
$this->m = memoize(function ($key) {
return "[$key]";
});
}
public $m;
}
$t = new Test;
// http://stackoverflow.com/questions/7067536/how-to-call-a-closure-that-is-a-class-variable
var_dump($t->m->__invoke('one'));
var_dump($t->m->__invoke('two'));
var_dump($t->m->__invoke('one'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment