PHP compile time generics: yay or nay?

https://news.ycombinator.com/rss Hits: 5
Summary

One of the most sought-after features for PHP is Generics: The ability to have a type that takes another type as a parameter. It's a feature found in most compiled languages by now, but implementing generics in an interpreted language like PHP, where all the type checking would have to be done at runtime, has always proven Really Really Hard(tm), Really Really Slow(tm), or both. But, experimentation by the PHP Foundation's dev team suggests we may be able to get 80% of the benefit for 20% of the work. Is that enough? The short, short version We believe it's possible to implement generics on only interfaces and abstract classes, which would offer a large chunk of the benefit of generics but avoid most of the pitfalls. In particular, interfaces and abstract classes could declare that they need one or more types specified: interface Exporter<Thing> { ... } And then classes that implement/extend them would be required to fill in those types: class WidgetExporter implements Exporter<Widget> { ... } And then anywhere the type Thing appeared in Exporter, it would turn into Widget in WidgetExporter. All of this is done at compile time, which makes it far easier and faster, and many/most errors would be caught at compile time. Runtime generics, where you could say $fooExporter = new Exporter<Foo>(), would still not be possible, but they do not get any harder as a result of going just part way. Would you support (and vote in favor of) compile-time-only generics as described below? Prior research In 2023 and 2024, Arnaud Le Blanc from the Foundation team did extensive experimentation on generics, picking up on the previous work from Nikita Popov. The full result of that experiment is available at that link, but in short, some parts of generics would be possible, even straightforward. Where the edge cases run into problems, though, they are very big problems. In particular: Union types and generics combine to produce massive performance penalties. Many cases would result in a v...

First seen: 2025-08-10 21:44

Last seen: 2025-08-11 01:44