Consider the following PHP code snippet. What will it output?
<?php class Profile { public ?string $email = null; } class User { public ?Profile $profile = null; } $user = new User(); echo $user->profile?->email ?? 'No email'; ?>
The null safe operator returns null if the left side is null, so the null coalescing operator will provide the fallback.
The ?-> operator safely accesses email only if profile is not null. Since profile is null, $user->profile?->email returns null, so the ?? operator outputs 'No email'.
Given the code below, what will be printed?
<?php class Engine { public ?string $type = 'V8'; } class Car { public ?Engine $engine = null; } $car = new Car(); echo $car->engine?->type ?? 'No engine'; ?>
Check if engine is set before accessing type.
The engine property is null, so $car->engine?->type returns null. The null coalescing operator then outputs 'No engine'.
Analyze the code below and select the correct output.
<?php class Address { public ?string $city = 'Paris'; } class User { public ?Address $address = null; public function getAddress(): ?Address { return $this->address; } } $user = new User(); echo $user->getAddress()?->city ?? 'Unknown city'; ?>
Consider what getAddress() returns and how the null safe operator works with method calls.
The method getAddress() returns null because address is null. The null safe operator prevents an error and returns null, so the null coalescing operator outputs 'Unknown city'.
What will this code output?
<?php class Book { public ?string $title = 'PHP Guide'; } $book = null; echo $book?->title; ?>
The null safe operator short-circuits when the left side is null and does not evaluate the right side.
Since $book is null, the null safe operator ?-> returns null immediately without attempting to call the non-existent title() method (note: title is a property, not a method). echo null; produces no output.
Consider this PHP code using null safe operator inside a loop. How many items will the $results array contain?
<?php class Item { public ?string $name; public function __construct(?string $name) { $this->name = $name; } } $items = [new Item('A'), null, new Item(null), new Item('D')]; $results = []; foreach ($items as $item) { $results[] = $item?->name ?? 'Unknown'; } print_r($results); ?>
Count how many times the loop runs and what values are added to $results.
The loop runs 4 times. For each $item, the null safe operator safely accesses name. If $item is null or name is null, 'Unknown' is added. So $results has 4 items.