PHP 7: Maintaining and Upgrading Legacy Apps · PHP 7 Language Essentials
PHP 7.1–7.3: Nullable, void, iterable and More
Nullable types, void, iterable, class constant visibility, multi-catch and list() improvements.
PHP 7.1 added nullable types (?string), the void return type, the iterable pseudo-type, class constant visibility, multi-catch (catch (A | B $e)), keyed list() and short array destructuring [$a, $b] = .... PHP 7.2 added the object type and Argon2 password hashing; 7.3 added flexible heredoc syntax, trailing commas in calls, array_key_first/last() and JSON_THROW_ON_ERROR.
<?php
final class UserService
{
private const CACHE_TTL = 300; // 7.1: visibility on constants
public function find(int $id): ?User // 7.1: nullable
{
// ...
}
public function logout(): void { /* ... */ } // 7.1: void
}
try {
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR); // 7.3
} catch (JsonException | InvalidArgumentException $e) { // 7.1 multi-catch
return badRequest($e->getMessage());
}
['id' => $id, 'email' => $email] = $row; // keyed destructuring
Common pitfalls
- Using
json_decode()without checkingjson_last_error()(or the throw flag) and gettingnullsilently. - Declaring
voidand still returning a value. - Relying on
iterableand then calling array functions on a Traversable.
Key points
- Nullable and void types (7.1)
- Multi-catch and destructuring
- JSON_THROW_ON_ERROR (7.3)
Further reading: PHP manual: PHP 7.1 new features
Practice questions
Why use JSON_THROW_ON_ERROR?
Answer
Without it, json_decode returns null on invalid input (indistinguishable from a JSON null) and you must check json_last_error(). With the flag, a JsonException is thrown.
Can an iterable parameter be passed to array_map()?
Answer
Not safely — iterable accepts arrays and Traversable objects, but array_map requires an array. Use iterator_to_array() or iterate with foreach.
Open in the app to mark lessons complete, take notes and track your progress.