Re: [Discussion] Revisiting typed closures
| From: | Matheus Martins | Date: | Wed, 01 Jul 2026 17:10:12 +0000 |
| Subject: | Re: [Discussion] Revisiting typed closures | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-131663@lists.php.net to get a copy of this message | ||
> 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?