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.

php Courses
php Courses
php Courses
Pure Intersection Types in PHP 8.1

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPtype-systemPHP8.1Intersection Types
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.