The __invoke() magic method in PHP allows an object to be called like a function. When an object is invoked using parentheses, PHP automatically executes the __invoke() method.
__invoke()The __invoke() method is declared inside a class and can accept any number of parameters. When the object instance is used as a function, this method executes.
// Define a class that can be called like a function
class Calculator {
public function __invoke($a, $b) {
return $a + $b;
}
}
// Create object and invoke it like a function
$calc = new Calculator();
echo $calc(5, 10);
The object $calc behaves like a function. When $calc(5, 10) is executed, PHP internally calls the __invoke() method and returns the sum 15.
Think of __invoke() as a bridge between object-oriented and functional programming. It allows objects to be passed as callbacks and executed dynamically.
__invoke() logic simple and focusedMultiplier class using __invoke()