Python Operators, Null Coalescing & Magic Constants
PHP provides an expressive suite of modern operators. Learn strict equality (===), the spaceship operator (<=>) for sorting, null coalescing (??) for fallback values, and built-in magic constants (__DIR__, __FILE__, __LINE__).
"The null coalescing operator (??) is like having a backup generator: if the main power line ($customSetting) is dead (null), it instantly falls back to the emergency power ($defaultSetting)."
Deep Dive: How It Works
Null Coalescing (??): $val = $input ?? "default"; returns $input if set and not null, otherwise "default".
Spaceship Operator (<=>): $a <=> $b returns -1 if $a < $b, 0 if $a == $b, and 1 if $a > $b (ideal for usort).
Magic Constants: Predefined constants that resolve at compile time (__DIR__, __FILE__, __LINE__, __CLASS__, __FUNCTION__).
Syntax Blueprint
<?php $port = $_ENV["PORT"] ?? 8080; $order = $a <=> $b; echo "Running in: " . __DIR__;
Use ?? for safe fallbacks, <=> for comparative ordering, and magic constants for filesystem metadata.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Confusing ternary (? :) with null coalesce (??).Why it happens: $a ?: $b triggers an undefined variable warning if $a does not exist, whereas $a ?? $b handles missing variables gracefully without warning.
How to fix: Use ?? when checking array keys or potentially unset variables.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Configure Default Server Port
Declare $customPort = null.
Use the null coalescing operator to assign $port = $customPort ?? 3000.
Print "Server listening on port: [port]".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.