Well, Edd Mann shows a great way to implement memoize function in php in His post
Here is a sample code (actually taken from a post by Edd Mann):
$memoize = function($func) { return function() use ($func) { static $cache = []; $args = func_get_args(); $key = md5(serialize($args)); if ( ! isset($cache[$key])) { $cache[$key] = call_user_func_array($func, $args); } return $cache[$key]; }; }; $fibonacci = $memoize(function($n) use (&$fibonacci) { return ($n < 2) ? $n : $fibonacci($n - 1) + $fibonacci($n - 2); });
Note that the global definition that it replaced is thanks to the clousure function and support for PHP first-class functions.
Another solution:
You can create a class containing both static elements: fibonnacciMemo and $memo . Note that you no longer need to use $memo as a global variable, so it will not conflict with other namespaces. Here is an example:
class Fib{ //$memo and fibonacciMemo are static members static $memo = array(); static function fibonacciMemo($n) { if(array_key_exists($n, static::$memo)) { return static::$memo[$n]; } else { if($n > 1) { $result = static::fibonacciMemo($n-1) + static::fibonacciMemo($n-2); static::$memo[$n] = $result; return $result; } return $n; } } } //Using the same method by Edd Mann to benchmark //the results $start = microtime(true); Fib::fibonacciMemo(10); echo sprintf("%f\n", microtime(true) - $start); //outputs 0.000249 $start = microtime(true); Fib::fibonacciMemo(10); echo sprintf("%f\n", microtime(true) - $start); //outputs 0.000016 (now with memoized fibonacci) //Cleaning $memo Fib::$memo = array(); $start = microtime(true); Fib::fibonacciMemo(10); echo sprintf("%f\n", microtime(true) - $start); //outputs 0.000203 (after 'cleaning' $memo)
Using this, you avoid using global , as well as the problem of clearing the cache. Although tt $memo not a stream preservation, and stored keys do not have hashed values. In any case, you can use all memoize php utilities like memoize-php
source share