Skip to content

Revisiting PHP 5.3 __invoke magic method

PHP version 5.3 introduced a new magic method designed __invoke, this method is called when a script tries to call an object as a function.

The __invoke magic method

By running this piece of code you can expect the following output:

I am an object of type: Car
Just called object as function with parameter 'ford'

As php cannot accommodate pseudo-first-class functions, the __invoke method can be used to suppress this language limitation. On other hand you can use this for simpler things as pass a function around.

This can be a neat feature of the language for some developers and a complete headache for others, because it will make the code less clean, in my opinion.

More details about the __invoke magic method on PHP Manual.

What's your experience with the __invoke method usage ?

Published inCodingphp


  1. It could be usefull when implementing the command or strategy pattern.

  2. osbertv osbertv

    Invoking a class inside a class results in an error.

    a = new A();

    public function __invoke()
    echo “Invoking B() Class”;

    $a = new A();
    $b = new B();


    Invoking B() Class
    PHP Fatal error: Call to undefined method B::a()

Leave a Reply

Your email address will not be published. Required fields are marked *