The Invoke Magic Method In PHP
I discovered a good use case of __invoke – that’s when a function expects a callable, e.g. spl_autoload_register.
In this case we often see implementation passes an anonymous function or a named function.
We can also craft a class which implements __invoke. It’s not too awkward to use.
Let’s compare these three methods.
<?php
function autoload($fqcn)
{
}
spl_autoload_register('autoload');
?>
<?php
spl_autoload_register(function ($fqcn) {
});
?>
<?php
class Autoload
{
public function __invoke($fqcn)
{
}
}
spl_autoload_register(new Autoload());
?>
The paragraphs above merely point out a fact that there is a third option when we implement a callable.
Yet this becomes interesting when you want to dynamically generate a callable for the function that expects a callable, e.g. spl_autoload_register.
<?php
function autoload_factory($namespace, $dir)
{
return function ($fqcn) use ($namespace, $dir) {
};
}
spl_autoload_register(autoload_factory('Example', 'src'));
?>
<?php
class AutoloadFactory
{
public function __construct($namespace, $dir)
{
}
public function __invoke($fqcn)
{
}
}
spl_autoload_register(new AutoloadFactory('Example', 'src'));
?>
That’s all!