Nov 4 2010

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

class Car {
	public function __invoke($v) 
		echo "Just called object as function with parameter '".$v."'\n";
$c	=	new Car;
// Just to make sure we have an object
echo "I am an object of type: ".get_class($c)."\n";
// Now let's use it as a function

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 ?

5 comments on “Revisiting PHP 5.3 __invoke magic method

  1. Pingback: This Week’s Link List (November 26, 2010) : Brian Swan's Blog : The Official Microsoft IIS Site

  2. Pingback: Programowanie w PHP » Blog Archive » Jose da Silva’s Blog: Revisiting PHP 5.3 __invoke magic method

  3. 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()

    osbertv on said:

Leave a Reply

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

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=""> <s> <strike> <strong>