Intermediate LevelPHP 8+
How do Union Types (int|string), Intersection Types (Countable&Traversable), and DNF Types (PHP 8.2) enhance type safety?
❓ Interview Prompt: Explain PHP 8.0 Union Types, PHP 8.1 Intersection Types, and PHP 8.2 Disjunctive Normal Form (DNF) types.
PHP type system support has evolved to express complex type constraints natively:
1. Union Types ('int|string') (PHP 8.0+):
Accepts values that match at least one of the specified types.
2. Intersection Types ('Countable&Traversable') (PHP 8.1+):
Requires values to satisfy ALL specified interfaces/types simultaneously.
3. Disjunctive Normal Form (DNF) Types (PHP 8.2+):
Allows combining Union and Intersection types using parenthesized notation: '(HasId&HasName)|null'.
Code Implementation Example
php
<?php
interface HasId { public function getId(): int; }
interface HasName { public function getName(): string; }
// PHP 8.2+ DNF Type: Must satisfy (HasId AND HasName) OR be null!
function renderUserHeader((HasId&HasName)|null $entity): string {
if ($entity === null) return "Guest";
return "User #" . $entity->getId() . ": " . $entity->getName();
}💡Expressing complex type constraints using PHP 8.2 Disjunctive Normal Form (DNF) types.
🎯 Interview Key Takeaway
Combine Union (|), Intersection (&), and DNF types to declare precise static type constraints in PHP signatures.
#Types#Union Types#DNF Types#PHP 8.2#Intermediate
Back to all PHP 8+ Questions→