Re: [PHP-DEV] [Discussion] Revisiting typed closures
[email protected] ("Matthew Weier O'Phinney")
| Newsgroups | php.internals |
|---|---|
| Message-ID | <CAJp_myV3+FnSGdyuBiveA4X7cTp=3Qd69uCS-V-T_8P3EHatMg@mail.gmail.com> |
On Wed, Jul 1, 2026, 12:11 PM Matheus Martins <[email protected]> wrote: > > I would rather wait for generics and possibly make Closure a generic > type. > > Fair point, but I am worried that's misleading, and I would keep the two > separate. > > Generics are a much larger and more contentious topic; typed closure is a > much > smaller topic: a runtime shape check on a Closure value at the boundary, > nothing > more. > > The concrete benefit is typing the callback a higher-order method takes, > so a mismatched map/filter callback is caught at the call site rather than > deep > inside the operation (or only by static analysis): > > ```php > // expected signature: (int) => bool > public function filter(Closure(int): bool $pred): static; > > // ok > $nums->filter(fn(int $n): bool => $n % 2 === 0); > > // TypeError: string not expected > $nums->filter(fn(string $s): bool => $s !== ''); > ``` > > Typed closures neither need generics nor blocks them. In fact, eventually > typed > closures will support generics. But I would rather keep these topics > separate. > > On its own, is a runtime-checked closure signature something you would find > useful? > I would find this very useful. That said, restricting it to closures and not any callable is very limiting, particularly now that we have first-class callable syntax. Perhaps something more along the line of : callable(int):bool This would give more flexibility, and provide us contract guarantees. Right now, SA can validate these, but only via annotations. -- Matthew Weier O'Phinney [email protected] https://mwop.net/ he/him >