Discover how union types can save you from messy type checks and bugs!
Why Union types in practice in PHP? - Purpose & Use Cases
Imagine you are writing a function that can accept either a number or a string. Without union types, you have to write extra code to check the type manually and handle each case separately.
This manual checking makes your code longer, harder to read, and easy to forget some cases. It also increases the chance of bugs because you might miss handling a type or mix up the logic.
Union types let you declare that a function or variable can accept multiple types directly. This means PHP will automatically check the types for you, making your code cleaner, safer, and easier to understand.
function process($input) {
if (is_int($input)) {
// handle int
} elseif (is_string($input)) {
// handle string
} else {
throw new Exception('Invalid type');
}
}function process(int|string $input) {
// handle int or string directly
}It enables writing flexible functions that clearly state what types they accept, reducing bugs and improving code readability.
For example, a function that formats user input can accept either a string or a number, and union types let you declare this clearly without extra checks.
Manual type checks make code long and error-prone.
Union types let you declare multiple accepted types simply.
This leads to cleaner, safer, and easier-to-read code.