PHP Reference ยท Functions and Classes
The __invoke() magic method
Reference for PHP __invoke(): make an object callable like a function, use it as a callback with array_map and usort, and convert it with Closure::fromCallable.
When a class defines __invoke(), its instances can be called like functions: $obj(1, 2) runs $obj->__invoke(1, 2). Such an object is also a valid callable, so it can be passed to array_map(), usort(), middleware pipelines and anywhere else a callback is accepted.
Unlike a plain closure, an invokable object can have its own state, constructor arguments, other methods and a name you can type-hint on. That makes it good for single-purpose classes such as validators, handlers and strategies.
class Multiplier { public function __construct(private int $factor) { } public function __invoke(int $n): int { return $n * $this->factor; } } $triple = new Multiplier(3); echo $triple(5); // 15
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
public function __invoke(parameters): returnType { // body } $object(...$arguments); // direct call $object->__invoke(...$arguments); // explicit call call_user_func($object, ...$arguments); // via callable
The method may take any parameters and return any type. It must be public and non-static is the normal form.
Return value: whatever __invoke() returns.
Errors: calling an object whose class has no __invoke() throws Error ("Object of type X is not callable").
Usage notes
callabletype: an object with__invoke()satisfies thecallabletype declaration, andis_callable()returnstrue.- Callback in arrays:
[$obj, '__invoke']also works, but$objalone is clearer. - Closures are invokable objects. The
Closureclass has an__invoke()method;$closure->__invoke()is the same as$closure(). - First-class callable syntax
$obj(...)(PHP 8.1) creates aClosurebound to the same object. - Single-action classes. Controllers or handlers with just one job are often written as invokable classes, so the class name is the action.
- Type safety: you can type-hint the class itself (
GreaterThan $rule) which is stricter thancallable. - Readability. If an object needs several public methods, give them real names; keep
__invokefor the one obvious action. - Static analysis understands
__invokesignatures, so parameter and return types are checked.