PHP 8 interview question · Most asked
What are union types in PHP 8 and how do you use them?
Summary
Union types let a parameter, return value or property accept one of several types, written TypeA|TypeB, and are enforced by the engine at runtime.
Longer Answer
Before PHP 8 you could only document "int or string" in a docblock. Union types make that a real contract the engine checks. Any combination of class/interface names and scalar types is allowed, plus null (so ?Foo is shorthand for Foo|null) and the special false pseudo-type (PHP 8.2 also allows standalone true, false and null).
Redundant types are compile-time errors (int|int), and void cannot be part of a union. Under coercive typing mode, PHP tries the types in a defined preference order (int, float, string, bool) when coercing scalars.
Code Example
<?php
declare(strict_types=1);
function formatId(int|string $id): string
{
return is_int($id) ? sprintf('#%05d', $id) : strtoupper($id);
}
echo formatId(42); // #00042
echo formatId('ab-1'); // AB-1
Key Points
- Syntax:
int|string,Foo|Bar|null ?Tis equivalent toT|nullvoidcan never be in a union- Prefer narrow unions; a wide union often signals a missing abstraction
Explanation
What interviewers look for
Knowing that unions are runtime-enforced (not just documentation) and that ?T is sugar for T|null.
Common mistakes
- Using
mixedwhen a two-member union would be more precise - Forgetting that
false(notbool) is allowed for legacy functions returningT|false
Follow-up questions
- What are DNF types (PHP 8.2)?
- How do intersection types differ?
More most-asked PHP 8 questions
- How should passwords be stored in PHP?
- What are the most important features introduced in PHP 8.0?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- What are enums in PHP 8.1? Explain pure vs backed enums.
- Explain readonly properties (8.1) and readonly classes (8.2).