← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Intersection & DNF Types in Practice

php PHP 8.1+ Advanced

TL;DR

PHP 8.1 intersection types (A&B) and PHP 8.2 DNF types ((A&B)|null) allow precise type constraints for objects implementing multiple interfaces.

Explanation

Intersection types (PHP 8.1): function process(Countable&Iterator $c) — $c must implement BOTH interfaces. Only works with class/interface types, not scalars. DNF (Disjunctive Normal Form) types (PHP 8.2): (Countable&Iterator)|null — unions of intersections. The DNF form requires intersections in parentheses inside unions. Use cases: utility functions that require an object to implement multiple interfaces, nullable intersection types. PHPStan and Psalm both support intersection types for static analysis.

Common Misconception

Intersection types work with scalar types like int&string — they only work with object types (classes and interfaces).

Why It Matters

Intersection types enable precise type constraints that were previously impossible — expressing 'must implement both A and B' without creating a new combined interface.

Common Mistakes

  • Using intersection with scalar types — fatal error.
  • Not using DNF parentheses for (A&B)|null — required syntax in PHP 8.2.
  • Confusing union (A|B = either) with intersection (A&B = both).

Code Examples

✗ Vulnerable
// Can't use intersection with scalars:
function foo(int&string $x) {} // Fatal Error
✓ Fixed
interface Serializable {}
interface Loggable {}

// Must implement BOTH:
function process(Serializable&Loggable $obj): void {}

// PHP 8.2 DNF — nullable intersection:
function maybe((Serializable&Loggable)|null $obj): void {}

Added 23 Mar 2026
Views 22
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 1 ping S 1 ping S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Amazonbot 6 Google 5 Perplexity 5 Unknown AI 3 ChatGPT 1 Ahrefs 1
crawler 16 crawler_json 3 pre-tracking 2
DEV INTEL Tools & Severity
🔵 Info ⚙ Fix effort: Medium
⚡ Quick Fix
Use A&B intersection for objects required to implement multiple interfaces. Use (A&B)|null for nullable with DNF syntax. Scalars not supported.
📦 Applies To
PHP 8.1+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
[A-Z][a-z]+&[A-Z]
Auto-detectable: ✓ Yes phpstan psalm
🤖 AI Agent
Confidence: Low False Positives: Medium ✗ Manual fix Fix: Low Context: Function

✓ schema.org compliant