patternphplaravelTip
PHP 8.1 Intersection Types for Precise Type Constraints
Viewed 0 times
PHP 8.1+
intersection typephp 8.1type systemCountableStringableDNFmultiple interfaces
Error Messages
Problem
Functions require an argument that satisfies multiple interfaces simultaneously. Before PHP 8.1 you could only express this with a comment or by creating a third combining interface, which is boilerplate.
Solution
Use intersection types with & to require a value that implements all listed interfaces: function process(Countable&Stringable $value). This is verified at the call site. Intersection types can only include class/interface types, not built-in types.
Why
Intersection types let you express precise constraints without creating glue interfaces. The type checker (static analysis tools and the runtime) ensures the value satisfies all constraints.
Gotchas
- Intersection types only allow pure intersection (A&B), not mixed with union (A|B&C) without grouping—PHP does not support DNF types until PHP 8.2
- PHP 8.2 introduces Disjunctive Normal Form (DNF) types: (A&B)|null
- Cannot use scalar types (string, int) in intersection types—only class and interface types
- Intersection types are not compatible with nullable shorthand (?Type)
Code Snippets
Intersection type parameter
interface Serializable {}
interface Loggable {}
function persist(Serializable&Loggable $entity): void
{
// guaranteed to implement both interfaces
}Revisions (0)
No revisions yet.