Nullsafe Operator and Union Types
Use ?-> to safely chain nullable objects and declare union type hints.
The Nullsafe Operator
PHP 8.0 introduced ?->. If the left-hand side is null, the entire chain short-circuits and returns null instead of throwing an error.
Problem it Solves
Without nullsafe, chaining nullable objects requires verbose null checks.
<?php
// Old way:
$city = null;
if ($user !== null && $user->getAddress() !== null) {
$city = $user->getAddress()->getCity();
}
// PHP 8 nullsafe:
$city = $user?->getAddress()?->getCity();All lessons in this course
- Match Expression and Named Arguments
- Nullsafe Operator and Union Types
- Enumerations (Enums)
- Fibers: Cooperative Concurrency