B. Error because getItem() is called on null without null safe operator.
C. Syntax error due to missing semicolon.
D. Error because null safe operator cannot be chained.
Solution
Step 1: Analyze the null safe operator chaining
The first null safe operator ?-> safely calls getItem() on $order which is null, so it returns null.
Step 2: Check the next method call
Then getName() is called on the result of getItem() without null safe operator, causing an error because it's called on null.
Final Answer:
Error because getItem() is called on null without null safe operator. -> Option B
Quick Check:
Chained calls need ?-> on each nullable step [OK]
Hint: Use ?-> before every nullable method call in chain [OK]
Common Mistakes:
Assuming one ?-> covers all chained calls
Ignoring that getName() is called on null
Thinking null safe operator fixes all errors automatically
5. Given the following PHP code, what will be the output?
class Profile {
public ?string $nickname = null;
}
class User {
public ?Profile $profile = null;
}
$user = new User();
$user->profile = new Profile();
$user->profile->nickname = null;
echo $user?->profile?->nickname ?? 'No nickname';
hard
A. No nickname
B. null
C. Error: Cannot access property on null
D. Empty string
Solution
Step 1: Trace object properties and null safe operator
$user is an object, $user->profile is an object, but $user->profile->nickname is null.
Step 2: Evaluate null safe operator and null coalescing
The expression $user?->profile?->nickname safely returns null because nickname is null. Then ?? 'No nickname' returns 'No nickname'.