PHP › Magic Methods
What does the __invoke magic method do, and how does it let you use an object instance directly as if it were a function?
IntermediateAnswer
The __invoke magic method lets you call an object instance directly using function call syntax, as if the object itself were a callable function, which is useful for creating classes that represent a single specific action or behavior, such as a single use case class in certain architectural styles, while still benefiting from being a full class that can hold configuration or dependencies through its constructor.
class Multiplier {
public function __construct(private float $factor) {}
public function __invoke($number) {
return $number * $this->factor;
}
}
$double = new Multiplier(2);
echo $double(5);Real-world example A single action controller class in a Laravel application implements __invoke, letting Laravel's router call the entire controller object directly as if it were a simple closure, keeping controllers focused on handling exactly one specific action.