- Version: 1.0
- RFC Type: Feature
- Author: Your Name
- Status: Draft
The purpose of this RFC is to propose the addition of generic types and type parameters to the PHP language. Generics provide a powerful mechanism for writing reusable and type-safe code by allowing the definition of generic classes, interfaces, and functions that can operate on a variety of types.
Currently, PHP does not have built-in support for generics, which limits the ability to write reusable and type-safe code. With the increasing complexity of modern PHP applications, the addition of generics would provide a significant improvement in code quality and maintainability.
-
Syntax for Generic Types and Type Parameters: The proposal introduces the use of angle brackets (<>) to denote generic types and type parameters. Type parameters are specified when declaring a generic class, interface, or function, allowing the code to operate on different types.
-
Declaring Generic Classes: A class can be declared as generic by specifying one or more type parameters in angle brackets after the class name. For example:
<?php class Collection<T> { // class implementation }
-
Using Generic Types: Generic types can be used in properties, method return types, and method parameter types. For example:
<?php class Collection<T> { private array $items = []; public function addItem(T $item): void { // method implementation } public function getItem(): T { // method implementation } }
-
Declaring Generic Interfaces: Interfaces can also be declared as generic, allowing the specification of type parameters that can be used by implementing classes. For example:
<?php interface Iterator<T> { public function next(): T; }
-
Implementing Generic Interfaces: When implementing a generic interface, the implementing class can either specify concrete types for the type parameters or rely on type inference. For example:
<?php class StringIterator implements Iterator<string> { // implementation }
-
Using Generic Functions: Generic functions can be declared by specifying type parameters before the function name. The type parameters can then be used in the function's return type and parameter types. For example:
<?php function reverse<T>(array $input): array { // function implementation }
The introduction of generics will not break backward compatibility with existing PHP code. Existing codebases will continue to function as before, and generics will be an opt-in feature.
This feature is proposed for inclusion in PHP 9.
The addition of generics to PHP would bring significant benefits to the language by enabling the creation of more reusable, type-safe, and maintainable code. It would provide developers with a powerful tool to write generic classes, interfaces, and functions that can operate on a variety of types.