PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

PHP's Magic __invoke() Method and the Callable Typehint

Note: This article was originally published at Planet PHP on 10 July 2012.
Planet PHP

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:

A class Butterfly { public function __invoke() { echo "flutter"; } }

We can instantiate a Butterfly object, and then just use it like a function:

A $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:

A function sparkles(Callable $func) { $func(); return "fairy dust"; } A class Butterfly { public function __invoke() { echo "flutter"; } } A $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:

Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist. This post was originally published at LornaJane