Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

A little memoize function in PHP

So, Caleb Porzio recently shared a little memoize function in PHP. What the function does is pretty straightforward.

It caches the result of a function call and returns the cached result if the function is called again with the same arguments.

Here’s the function.

function memoize($target) 
{
    static $memo = new WeakMap;

    return new class ($target, $memo) {
        function __construct(
            protected $target,
            protected &$memo,
        ) {}

        function __call($method, $params)
        {
            $this->memo[$this->target] ??= [];

            $signature = $method . crc32(json_encode($params));

            return $this->memo[$this->target][$signature]
               ??= $this->target->$method(...$params);
        }
    };
}

And here’s how you can use it.

class User 
{
    private function getViewCount()
    {
        return DB::table('users')->count();
    }
}

$user = new User;

// saves the result of the first call
$viewCount = memoize($user)->getViewCount(); 

// returns the cached result
$viewCountAgain = memoize($user)->getViewCount(); 

As you can tell, the function takes a target object as the first argument and returns a new class instance on which you can call the methods of the target object.

Essentially, the function creates a new class instance and leverages the __call() magic method to call the method on the target object. It then caches the result of the method call and returns the cached result if the method is called again with the same arguments.

It uses WeakMap to cache the result of the method call. This is because WeakMap doesn’t hold a reference to the key. So, when the key is no longer referenced, it will be removed from the map and the memory will be freed.

Pretty intriguing little function, isn’t it?

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?