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:

merlin

6 thoughts on “PHP's Magic __invoke() Method and the Callable Typehint

  1. 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 ...;
    }
    }

  2. 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.

  3. just want to say that what is true one day is a not next day, or it was never true :)
    a lot of invoke usage in architectures EBI with interactors on silex, symfony2 and libraries.

  4. The Callable type hint is awesome but what if I want to check in an if/else situation?
    instanceof Callable does not appear to work.
    <?php

    $bob = "blah";

    if($bob instanceof Callable) {
    echo "x";
    }

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>