Module 16: PHP Type System – AdvancedIntermediate50 min read
PHP 8 Type System: Union, Intersection, never, mixed & Variance
Master PHP 8.0 Union types, PHP 8.1 Intersection types (A&B) & never return type, PHP 8.2 DNF types, and LSP covariance/contravariance.
Key Takeaways & Core Concepts
- Union Types (PHP 8.0):
int|float|string - Intersection Types (PHP 8.1):
Countable&Iterator(object must satisfy both interfaces). - `mixed` (PHP 8.0): Equivalent to
object|resource|array|string|int|float|bool|null. - `never` (PHP 8.1): Function never returns (always throws or calls
exit).
1. Modern PHP Type Constructs
- Union Types (PHP 8.0):
int|float|string - Intersection Types (PHP 8.1):
Countable&Iterator(object must satisfy both interfaces). - `mixed` (PHP 8.0): Equivalent to
object|resource|array|string|int|float|bool|null. - `never` (PHP 8.1): Function never returns (always throws or calls
exit).
1. Union Types & never Return Type (PHP 8.1)
1<?php
2declare(strict_types=1);
3
4function formatId(int|string $id): string {
5 return "ID-" . strtoupper((string)$id);
6}
7
8echo formatId(101) . " | " . formatId("abc") . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
8 lines
Note: Accepts either `int` or `string` cleanly using PHP 8.0 union types.
2. Type Variance (Liskov Substitution Principle)
Child methods may widen parameter types (contravariance) and narrow return types (covariance).
Practice & AssessmentPHP Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)