Memoizing recursive functions in PHP without static variables
The usual way to memoize a recursive function in PHP is a static variable inside the function. It works, but it is process-global state which causes problems in Swoole where workers are reused. Here is a cleaner approach using closures.
The cache lives inside the closure, so it is scoped to the $fib variable. Create a new $fib and you get a fresh cache. No shared state across requests.
Nice pattern. One addition: the serialize() key works but is slow for large arguments. For functions that only take scalar args a much faster key is just implode("\0", func_get_args()).
Worth mentioning: this pattern has a subtle issue with the use (&$fib) reference. If you reassign $fib to a different function later, the recursive calls inside still use the old reference because &$fib captures the variable binding, not the value. In practice this rarely matters but it can produce surprising results in tests if you reuse the variable name.
To make it fully safe, use a wrapper object or just avoid reassigning the variable after creation.
```php blocks are runnable.