__invoke

PHP does not allow the passing of function pointers like other languages. Functions are not first class in PHP. Functions being first class mainly means that you can save a function to a variable, and pass it around and execute it at any time.

The __invoke method is a way that PHP can accommodate pseudo-first-class functions.

The __invoke method can be used to pass a class that can act as a closure or a continuation, or simply as a function that you can pass around.

The __invoke() method is called when a script tries to call an object as a function.

<?php
 class Invoke {
 public function __invoke($x)
 {
 var_dump($x);
 }
 }
 $obj = new Invoke;
 $obj(5);
?>
Share

Leave a Reply

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