Pure Intersection Types in PHP 8.1
The article explains PHP 8.1’s pure intersection types, how they differ from union types, demonstrates their use with an example function that combines multiple interfaces, and provides links to the official RFC and related PHP 8.1 feature articles.
Pure intersection types are a new feature introduced in PHP 8.1. While union types accept a value that matches any one of the listed types, intersection types require the value to satisfy all specified types simultaneously.
This is especially useful when a function needs to work with objects that implement several interfaces. For example, the following function accepts a parameter that implements both HasTitle and HasId interfaces, allowing it to generate a slug from the title and identifier:
function generateSlug(HasTitle&HasId $post) { return strtolower($post->getTitle()) . $post->getId(); }
Without intersection types, developers would have to create a new interface (e.g., Sluggable ) that extends the required interfaces, adding extra boilerplate. Intersection types eliminate this overhead.
For the full specification, see the RFC: https://wiki.php.net/rfc/pure-intersection-types .
Related articles that explore other PHP 8.1 features include:
PHP 8.1 Enums
PHP 8.1 Readonly Properties
PHP 8.1 Initializers
PHP 8.1 Fibers
PHP 8.1 Array Unpacking with String Keys
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.