PHP 7 interview question · Most asked
What are nullable types in PHP 7.1?
Summary
Prefixing a type with ? (e.g. ?string) allows the value to be either that type or null, for parameters and return types.
Longer Answer
Before 7.1 the only way to accept null was a = null default, which also made the parameter optional. ?string $name is required but may be null. (Implicit nullability via = null defaults was deprecated in PHP 8.4.)
Code Example
<?php
function findUser(int $id): ?User
{
return $this->users[$id] ?? null;
}
function greet(?string $name): string
{
return 'Hello ' . ($name ?? 'guest');
}
Key Points
?Tmeans T or null- Different from an optional parameter
- Works for params and return types
- Typed properties (7.4) also support
?T
More most-asked PHP 7 questions
- What are typed properties in PHP 7.4?
- What are arrow functions in PHP 7.4 and how do they differ from closures?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- How do return type declarations work in PHP 7?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- What are the main breaking changes when upgrading from PHP 7.4 to 8.0?