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.
Practice
int|string mean in PHP?Solution
Step 1: Understand union type syntax
The|symbol means the value can be one of the listed types.Step 2: Interpret
This means the value can be either an integer or a string, not both simultaneously.int|stringFinal Answer:
The value can be either an integer or a string. -> Option DQuick Check:
Union typeint|stringmeans either int or string [OK]
- Thinking the value must be both types at once
- Confusing union with intersection types
- Assuming only one type is allowed
Solution
Step 1: Identify correct union type syntax
Union types use|between types, soarray|nullis correct.Step 2: Check default value for nullable parameter
To accept null, the parameter should default to null, so$data = nullis needed.Final Answer:
function example(array|null $data = null) {} -> Option AQuick Check:
Union type with default null = correct syntax [OK]
- Using & instead of | for union
- Missing default null for nullable parameter
- Using ? without type for union
function describe(mixed $value): string {
return match (gettype($value)) {
'integer' => 'Number: ' . $value,
'string' => 'Text: ' . $value,
default => 'Unknown type'
};
}
echo describe(10) . ', ' . describe('hello') . ', ' . describe(3.14);Solution
Step 1: Analyze the match expression with gettype()
For 10, gettype returns 'integer', so output is 'Number: 10'. For 'hello', gettype returns 'string', so output is 'Text: hello'. For 3.14, gettype returns 'double', which matches default case 'Unknown type'.Step 2: Combine outputs
Outputs joined by commas: 'Number: 10, Text: hello, Unknown type'.Final Answer:
Number: 10, Text: hello, Unknown type -> Option AQuick Check:
Match on gettype gives expected strings [OK]
- Assuming float is treated as integer
- Ignoring default case in match
- Confusing gettype return values
function process(int|string $input): int {
if (is_string($input)) {
return strlen($input);
} else {
return $input + 1;
}
}
process(true);Solution
Step 1: Check parameter type declaration
The function expectsint|string, so only integers or strings are allowed.Step 2: Analyze the call with
Passingtruetrue(boolean) violates the declared union type, causing a TypeError at runtime.Final Answer:
Passing a boolean to a parameter expecting int|string causes a TypeError. -> Option CQuick Check:
Type mismatch causes error [OK]
- Ignoring type mismatch errors
- Thinking is_string is invalid syntax
- Assuming function return type is wrong
Solution
Step 1: Check union type declaration
Bothstring|arrayandarray|stringare valid syntax.Step 2: Verify handling of each type
function joinStrings(string|array $input): string { if (is_array($input)) { return implode(', ', $input); } return $input; } checks if input is array, then joins withimplode. If input is string, returns it directly. This correctly handles both cases.Step 3: Identify errors in other options
function joinStrings(string|array $input): string { return implode(', ', $input); } tries to implode without checking type, causing error if input is string. function joinStrings(string|array $input): string { if (is_string($input)) { return implode(', ', $input); } return $input; } incorrectly calls implode on string input. function joinStrings(array|string $input): string { if (is_array($input)) { return $input; } return implode(', ', $input); } returns array directly without joining.Final Answer:
function joinStrings(string|array $input): string { if (is_array($input)) { return implode(', ', $input); } return $input; } -> Option BQuick Check:
Check type then handle accordingly [OK]
- Calling implode on string input
- Returning array instead of string
- Not checking input type before processing
Ready to prove it?
Pass the test and this pattern moves unknown
