PHP invoke: is anybody using it?

Luís Nóbrega
4 min readJan 25, 2020

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.

Definition on PHP.net:

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

--

--

Luís Nóbrega
Luís Nóbrega

Written by Luís Nóbrega

Web Developer at 25friday. Likes to travel, write and being a father.

Responses (2)