__invoke() Magic Method in PHP
There are various magic methods that will make our work easier in PHP. Magic methods begin with two underscores(__construct, __invoke). In this post, I will explain the __invoke() magic method and its usage, which is frequently used in PHP.
__invoke() :
The __invoke is a method that we define in the class. If we call the object as a function after instantiating an object from the class, the method to be called is the __invoke() method.
Example:
First we will define a class named Car.
class Car{
public function __construct(){
echo "object created <br>";
}
public function __invoke(){
echo "invoke method called";
}
}Let’s create an object of this class. When we create an object, the __construct method will run. If we then call the object as a function, the __invoke method will run.
$obj = new Car(); $obj(); //Output: object created //Output: invoke method called
We can check whether the object is callable with the is_callable() function before calling it.
echo is_callable($obj) ? 'yes' : 'no'; //Output : yes
Callable Typehint
The callable typehint checks whether the thing being called is callable or not so that it is executed. It came with PHP 5.4. Below you will see a usage of how to use the __invoke magic method.
function start_engine(Callable $func) {
$func();
return "engine started";
}
$obj = new Car();
echo start_engine($obj);
//Output: object created
//Output: invoke method called
//Output: engine startedGood Luck …