PHP compile time generics: yay or nay?
17 days ago
- #PHP
- #Programming
- #Generics
- Generics in PHP are highly sought after but challenging to implement due to PHP being an interpreted language.
- The PHP Foundation's dev team suggests implementing generics on interfaces and abstract classes for 80% benefit with 20% effort.
- Compile-time generics would allow interfaces and abstract classes to declare required types, with implementing classes specifying them.
- Runtime generics (e.g., `new Exporter<Foo>()`) would remain impossible, but compile-time generics avoid most pitfalls.
- Experiments by Arnaud Le Blanc and Gina Banyard explored generics and associated types, focusing on compile-time solutions.
- Associated types allow interfaces to specify that inheritors must define a type, offering a simpler alternative to full generics.
- Manual monomorphization enables compile-time type enforcement, with classes specifying types for generic interfaces.
- Potential extensions include allowing abstract classes to be generic and supporting type declarations in method signatures.
- Common uses of generics, like typed collections, could be implemented with interfaces like `Sequence<T>`, `Set<T>`, and `Dict<K, V>`.
- Future possibilities include variance annotations (`in` and `out`) for generic types, but these are complex and may come later.
- Traits and functions with generics present additional challenges and are unlikely in initial implementations.
- Hard problems like runtime generics, union types with generics, and type inference remain unsolved and may never be feasible.
- The PHP Foundation seeks community feedback on whether compile-time-only generics are worth further development.