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

  • ?T means 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

← All PHP 7 questions