0PricingLogin
PHP Academy · Lesson

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

  1. Match Expression and Named Arguments
  2. Nullsafe Operator and Union Types
  3. Enumerations (Enums)
  4. Fibers: Cooperative Concurrency
← Back to PHP Academy