#65 - Function with internal state in PHP

Date: 2019-06-15 12:00 - PHP

Example of a function with internal state in PHP. Multiple calls to the function will yield different results.

<?php
function fib() {
    $a = 0;
    $b = 1;
    return function() use(&$a, &$b) {
        $c = $a + $b;
        $a = $b;
        $b = $c;
        return $c;
    };
}

$fib = fib();
echo $fib(); // 1
echo $fib(); // 2
echo $fib(); // 3
echo $fib(); // 5
echo $fib(); // 8

Previous snippet | Next snippet