Member-only story
PHP invoke: is anybody using it?
Spoiler Alert: Yes, I found several interesting and practical cases. I will share them with you in this post.
PHP has several functions that are called magic methods.
And why they are magic?
Because they are magically called by PHP when specific actions happen.
You can easily identify them because their names start with two underscores.
In the case of invoke, he’s called when an object is called as a function.
The __invoke() method is called when a script tries to call an object as a function.
He was made available on PHP 5.3, and on 5.4 arrived the type hint Callable that allows defining an argument as callable. As in the example below.
function foo(Callable $function) {
$function();
return “Hello!”;
}
So a callable could be a closure, invokable, or a valid callback.
You have also the PHP function is_callable to check if the variable is a callable.
But let’s check some use cases.
#1 Class with an obvious action method
It happens, when we have for example a provider. What does he do? It provides. Nothing more, nothing less.
Let’s look at AWS SDK for PHP, specifically to PatternEndpointProvider class.

It uses invoke to provide, using some arguments, an endpoint. How can we use this class?
Checking his unit tests, we can have a good look at it.
Another good example is Aura, a dispatcher package.
Provides tools to map arbitrary names to dispatchable objects, then to…