Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DynamicClosure {
- public static function execute(Closure $closure) {
- return call_user_func($closure);
- }
- }
- echo '<br/>Standard factorial<br/>';
- function factorial($n) {
- echo 'call <br/>';
- if ($n == 0) {
- return 1;
- } else {
- return $n * factorial($n - 1);
- }
- }
- echo factorial(10) . '<br/>'; // called 11 times
- echo factorial(11) . '<br/>'; // called 12 times
- echo factorial(8) . '<br/>'; // called 8 times
- echo '<br/>Memoized factorial<br/>';
- $memoizedFactorial = DynamicClosure::execute(function(){
- // results are cached in an array
- $results = array();
- // the function is passing itself as a bound variable
- return $factorial = function($n) use(&$results, &$factorial) {
- echo 'call <br/>';
- if (!isset($results[$n])) {
- if ($n == 0) {
- $results[$n] = 1;
- } else {
- $results[$n] = $n * $factorial($n - 1);
- }
- }
- return $results[$n];
- };
- });
- echo $memoizedFactorial(10) . '<br/>'; // called 11 times
- echo $memoizedFactorial(11) . '<br/>'; // called only 2 times!
- echo $memoizedFactorial(8) . '<br/>'; // called only 1 times!
Add Comment
Please, Sign In to add comment