Composite Type¶
Composite types combine multiple types into a single type expression. PHP supports three forms of composite types:
Union types (
A|B): the value must satisfy at least one of the listed types. Introduced in PHP 8.0, withcatchclauses supporting multi-type syntax since PHP 7.1.Intersection types (
A&B): the value must satisfy all of the listed types simultaneously. Restricted to class and interface names. Introduced in PHP 8.1.DNF types (
(A&B)|C): Disjunctive Normal Form, which combines intersections and unions. Introduced in PHP 8.2.
Composite types are accepted in parameter types, property types, and return types. catch clauses accept union types only. instanceof does not accept any composite form.
<?php
// Union type
function foo(int|string $id): void {}
// Intersection type
function bar(Countable&Iterator $col): void {}
// DNF type
function baz((Countable&Iterator)|null $col): void {}
?>
See also PHP type system: composite types, PHP RFC: Union Types 2.0, PHP RFC: Pure intersection types and PHP RFC: Disjunctive Normal Form Types.
Related : Union Type, Intersection Type, Disjunctive Normal Form (DNF), Named Type, Type System, Property Type Declaration, Return Type, Parameter
Added in PHP 8.0