Home » Releases » PHP 7.1 »

PHP 7.1 Code Comparisons

Explore PHP 7.1

Nullable Type Declarations

PHP 7.1 introduces nullable types. By prefixing type declarations with a question mark, functions and methods can explicitly accept or return either an instance of the specified type or null.
Before PHP 7.1
/**
 * @return User|null
 */
function find(int $id)
{
    return null;
}
PHP 7.1 or Later
function find(int $id): ?User
{
    return null;
}

Void Return Type

PHP 7.1 adds the void return type. Functions declared with : void must not return any value; returning anything other than nothing results in a fatal error.
Before PHP 7.1
function save(User $user)
{
    // Performs save operation
}
PHP 7.1 or Later
function save(User $user): void
{
    // Performs save operation
}

Iterable Pseudo-Type

PHP 7.1 introduces the iterable pseudo-type. It can be used in parameter and return type declarations to accept any array or object implementing Traversable, streamlining collection handling.
Before PHP 7.1
function process($items)
{
    foreach ($items as $item) {
        // ...
    }
}
PHP 7.1 or Later
function process(iterable $items): void
{
    foreach ($items as $item) {
        // ...
    }
}

Catching Multiple Exception Types

Catching multiple exception types in a single block allows handling different exceptions that require identical recovery or logging logic without duplicating catch blocks or resorting to catching top-level base exceptions like Throwable. Exceptions are separated using the pipe character (|), followed by a single variable that receives the caught exception instance.
Before PHP 7.1
try {
    $client->send();
} catch (NetworkException $e) {
    $logger->error($e->getMessage());
} catch (ServerException $e) {
    $logger->error($e->getMessage());
}
PHP 7.1 or Later
try {
    $client->send();
} catch (NetworkException | ServerException $e) {
    $logger->error($e->getMessage());
}