Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Null-safe access (?->)

Read a property or invoke a method only if the receiver is not null.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

$object?->method()

Read a property or invoke a method only if the receiver is not null. A null receiver short-circuits the chain and returns null without evaluating method arguments. Use another null-safe access wherever an intermediate result can itself be null. The operator cannot be used to write a property.

$object?->method()
["a@example.test",null,0]

Examples

<?php
$user = (object)['contact'=>(object)['email'=>'a@example.test']];
$guest = null;
$calls = 0;
$unused = $guest?->notify(++$calls);
echo json_encode([$user?->contact?->email, $guest?->contact?->email, $calls]);

Result

["a@example.test",null,0]

Sources