What if your code could accept different types without messy checks and bugs?
Why Union types 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 separate functions or add lots of checks everywhere to handle each type manually.
This manual approach is slow and error-prone because you must constantly check the type and write duplicate code. It's easy to forget a case or make mistakes, leading to bugs and confusing code.
Union types let you declare that a function or variable can accept multiple types directly. This makes your code clearer, safer, and easier to maintain because the language itself knows what types are allowed.
function process($value) {
if (is_int($value)) {
// handle int
} elseif (is_string($value)) {
// handle string
} else {
throw new Exception('Invalid type');
}
}function process(int|string $value) {
// handle int or string directly
}Union types enable writing flexible and robust code that clearly communicates what types are accepted, reducing bugs and improving readability.
For example, a function that formats user input might accept either a string or an integer ID. Union types let you declare this clearly so the function works smoothly with both.
Manual type checks are slow and error-prone.
Union types let you accept multiple types cleanly.
This leads to clearer, safer, and easier-to-maintain code.