Skip to content
Advertisement

Memoizing fibonacci function in php

I’ve created a memoized function of the recursive version of fibonacci. I use this as an example for other kinds of functions that would use memoization. My implementation is bad since if I include it in a library, that means that the global variable is still seen..

This is the original recursive fibonacci function:

JavaScript

and I modified it to a memoized version:

JavaScript

I purposely didn’t use the iterative method in implementing fibonacci. Is there any better ways to memoize fibonacci function in php? Can you suggest me better improvements? I’ve seen func_get_args() and call_user_func_array as another way but I can’t seem to know what is better?

So my main question is: How can I memoize fibonacci function in php properly? or What is the best way in memoizing fibonacci function in php?

Advertisement

Answer

Well, Edd Mann shows an excellent way to implement a memoize function in php in His post

Here is the example code (actually taken from Edd Mann’s post):

JavaScript

Notice that the global definition it’s replaced thanks to function clousure and PHP’s first-class function support.

Other solution:

You can create a class containing as static members: fibonnacciMemo and $memo. Notice that you don’t longer have to use $memo as a global variable, so it won’t give any conflict with other namespaces. Here is the example:

JavaScript

Using this, you avoid the use of global and also the problem of cleaning the cache. Althought, $memo is not thread save and the keys stored are no hashed values. Anyways, you can use all the php memoize utilites such as memoize-php

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement