Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Intersection Type

Intersection types, also called intersectional types, is a specification syntax where several types act together as a single type. The individual types are separated with the & operator.

The value typed with an intersection type must satisfy all the types at the same time.

Intersection types only accept class and interface types: scalars, int, string, bool, etc., null, false, true, and void are not allowed, as a single value cannot simultaneously be of two scalar types. Redundant types are also rejected: A&A is not valid.

Intersection types work well with polymorphism: an object that implements multiple interfaces satisfies an intersection type naturally.

PHP 8.2 introduced Disjunctive Normal Form, aka DNF, types, which combine intersection and union types, such as (A&B)|null.

<?php

    class X {
        // Property is of type A, B and C at the same time. 
        // Two of them have to be interfaces.
        private A & B & C $property;
    }

?>

Documentation

See Also