PHP's Magic __invoke() Method and the Callable Typehint
PHP has a variety of magic methods; methods named with two underscores at the start, which get called automatically when a particular event happens. In PHP 5.3, a new magic method was added: __invoke().
__invoke()
The __invoke() method gets called when the object is called as a function. When you declare it, you say which arguments it should expect. Here's a trivially simple example:
class Butterfly { public function __invoke() { echo "flutter"; } } |
We can instantiate a Butterfly object, and then just use it like a function:
$bob = new Butterfly(); $bob(); // flutter |
If you try to do the same thing on an object without an __invoke() method, you'll see this error:
PHP Fatal error: Function name must be a string in filename.php on line X
We can check if the object knows how to be called by using the is_callable() function.
Callable Typehint
In PHP 5.4 (the newest version, and it has lots of shiny features), we have the Callable typehint. This allows us to check whether a thing is callable, either because it's a closure, an invokable object, or some other valid callback. Another trivial example to continue the butterflies and kittens theme:
function sparkles(Callable $func) { $func(); return "fairy dust"; } class Butterfly { public function __invoke() { echo "flutter"; } } $bob = new Butterfly(); echo sparkles($bob); // flutterfairy dust |
So there it is, one invokable object being passed into a function and successfully passing a Callable typehint. I realise I also promised kittens, so here's a cute silver tabby I met the other day:


Btw, pretty much nobody uses __invoke in PHP, but it is something very common in other languages. E.g. in C++ you commonly define Functor classes:
class Hasher {
unsigned long operator()(const Obj& obj1, const Obj& obj2) {
return ...;
}
}
Very interesting - didn' t know about this new method.
This page served as a good intro to magic methods in general - thought i would share:
http://www.programmerinterview.com/index.php/php-questions/php-what-are-magic-functions/
Thank you Lorna, I needed to know exactly why and how the __invoke() method in ZF 2 helpers works. This post was the third in search results and the first with a good title.
@Nikita Everybody using ZF 2 with view helpers uses __invoke a lot.