PHP 8 Intermediate Language Basics · 7 min read

The PHP Nullsafe Operator

Lesson 26 of 43 in the PHP 8 learning path.

How do I call a method when the object might be null?

The nullsafe operator ?-> calls a method or reads a property only when the value on the left is not null. If the instructor is null, the chain stops and the whole expression is null. It does not call displayName, and it does not warn. Combine it with ?? when the page needs a visible default such as Unassigned.

Use it for a relationship that is allowed to be missing. If a lesson must have an instructor, load that instructor and fail with a clear error instead of printing a default forever. Nullsafe does not replace an empty string, and it cannot appear on the left of an assignment.

Syntax & Parameters

Syntax
$lesson->instructor?->displayName() ?? 'Unassigned'

Example

src/Lesson.php
<?php

declare(strict_types=1);

final class Instructor
{
    public function __construct(private string $name)
    {
    }

    public function displayName(): string
    {
        return $this->name;
    }
}

final class Lesson
{
    public function __construct(
        private string $title,
        private ?Instructor $instructor,
    ) {
    }

    public function title(): string
    {
        return $this->title;
    }

    public function instructor(): ?Instructor
    {
        return $this->instructor;
    }
}

function instructorName(Lesson $lesson): string
{
    return $lesson->instructor()?->displayName() ?? 'Unassigned';
}

$assigned = new Lesson('Routes', new Instructor('Ada'));
$open = new Lesson('Queries', null);

echo instructorName($assigned) . "\n";
echo instructorName($open) . "\n";

$raw = $open->instructor()?->displayName();
echo 'raw ' . ($raw === null ? 'null' : $raw) . "\n";
echo 'title ' . $open->title() . "\n";

Expected Output

Ada
Unassigned
raw null
title Queries

Line-by-Line Walkthrough

  1. Instructor stores a name, and displayName returns it. The method is only safe to call on a real object.
  2. Lesson stores a title and an instructor that is typed as nullable.
  3. instructor() returns that object or null. title() is an ordinary call because the title is always present.
  4. The first lesson is built with an Instructor named Ada. The second lesson passes null.
  5. instructorName calls displayName through ?-> and replaces a null result with Unassigned.
  6. On the assigned lesson the method runs, and the printed name is Ada.
  7. On the open lesson the operator stops. displayName is not called, the chain is null, and ?? supplies Unassigned.
  8. The raw read keeps null so a missing instructor is different from a name that was actually stored.
  9. The echo prints raw null. PHP does not attempt a method call on the null instructor.
  10. The title still prints, because that call is not behind the nullsafe operator. Only the instructor chain is optional.

Common Pitfalls & Security

Nullsafe hides absence. That is correct for an optional instructor and wrong for a field the page cannot render without.

  • ?? replaces only null. An instructor whose name is an empty string still shows that empty string.
  • You cannot assign through ?->. Writing a name onto a missing instructor needs an explicit branch that creates the object.
  • A long chain of ?-> usually means the data shape should be fixed, not papered over at every call.
  • Nullsafe does not validate the type. A wrong object that happens to be non-null still gets the method call.
  • Do not use a default name to skip an authorization decision. Missing is not the same as "guest is allowed".
  • Short ternary and ?: treat more values as empty. Use ?? when null is the only missing case.

Best Practices & Modern Standards

Keep the chain short: one optional relationship, then a method or a property, then ?? if the screen needs a fallback. Name the result. A variable called instructorName is easier to read than the operator buried in a template.

When the relationship is required, do not call through ?->. Load it, and if it is null, return a 404 or a validation error before the page renders. Reserve nullsafe for absence that is part of the model.

Real-World Use

A draft lesson has no instructor yet. The roster prints Unassigned instead of calling displayName on null. Routes still prints Ada, and the lesson title is read with a normal method call because the title is required.

Frequently Asked Questions

When does the chain stop?

When the value before ?-> is null. The method is not called, and the expression result is null. A real object runs the method as usual.

Can I assign through the nullsafe operator?

No. The operator is only for a read or a call. Create the missing object in a normal branch, then assign.

How is this different from ?? ?

?-> stops a call on null. ?? replaces a null result with a default. They are often used together, and neither one treats an empty string as missing.

Does nullsafe catch a missing method?

No. If the object exists and the method does not, PHP still raises an error. The operator only skips the call when the object itself is null.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…