A practical use case of anonymous classes in PHP
Anonymous classes in PHP let you create a class on the fly without having to define a new class. They are especially useful when you want to create a class that is only used once.
In my previous article, we checked out a memoize
helper function that uses anonymous classes to cache the result of a function call.
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);
}
};
}
Notice, the function makes use of PHP’s __call()
magic method to call the method on the target object to its advantage. And since, you can only use the __call()
magic method on a class, using anonymous classes come into play.
Imagine if you have to implement the same logic using regular classes. You would have to define a class and then implement the __call()
magic method on it.
Here’s an equivalent class that does the same thing as the anonymous class above.
class Memoize
{
function __construct(
protected $target,
protected &$memo,
) {}
public function __call($method, $params)
{
$this->memo[$this->target] ??= [];
$signature = $method . crc32(json_encode($params));
return $this->memo[$this->target][$signature]
??= $this->target->$method(...$params);
}
}
As you can tell, this is not a helper function anymore that you can just “drop-in” and start using it. You would have to define a class and then instantiate it and then call the method on that object. That’s a lot of boilerplate code for a simple helper function and the handiness is lost.
Anonymous classes solve problems like this. They allow you to create a class on the fly and use it to your advantage. And that’s exactly what the memoize()
function does.
So, in gist, when we have a use case where we want to utilize class features in the independent functions but you don’t want to define a standalone class, anonymous classes are the way to go.
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.