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

< ?php
 
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
$c('ford');


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

5 Comments

  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();
    $a();
    $b();
    $b->a();

    ?>

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

Leave a Reply to php training kolkata Cancel reply

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