Created
February 2, 2012 03:32
-
-
Save yhirose/1721247 to your computer and use it in GitHub Desktop.
PHP Lambda based memoizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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