Allow an object to be called as a function.
The __invoke() magic method is called when an object is used as a function. This allows objects to behave like callable functions while maintaining internal state.
This pattern is useful for creating configurable callbacks, middleware, single-action classes, and strategy patterns. Objects with __invoke() pass is_callable() checks and can be used anywhere a callable is expected.
The method can accept any number of parameters and return any type. It effectively turns a class into a functor, a common pattern in functional programming.
| Name | Description | Optional |
|---|---|---|
...args |
Any parameters passed when calling the object as a function. | Yes |
class Multiplier {
public function __construct(private int $factor) {}
public function __invoke(int $value): int {
return $value * $this->factor;
}
}
$double = new Multiplier(2);
echo $double(5); // 10
echo $double(10); // 20
$result = array_map($double, [1, 2, 3]);
// [2, 4, 6]