Coding/Learn/php/php operators and magic constants
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnOperators, Null Coalescing & Magic Constants
4 / 20 0%
Lesson 04 of 20
8 mins read

Operators, Null Coalescing & Magic Constants

PreviousNext Lesson
In Plain English

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 Mental Model

"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.

PointCore Rules to Remember

Point star
Strict Equality (===): Always prefer === over == to prevent unexpected type juggling bugs (e.g. 0 == "abc" was true in older PHP versions).
Point star
Null Coalescing Assignment (??=): $config["timeout"] ??= 30 assigns 30 only if the key is not already set.
Point star
Magic Constants: Always resolve relative to the file location, making __DIR__ ideal for robust file requires.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use PHP 8 nullsafe operator ($user?->profile?->avatar) to safely navigate nullable object chains without nested if checks.

Live Interactive Example

Hit Run Code to see it live
Null Coalescing and Spaceship Comparison
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: ?? safely picked "dark_slate" because $userPreference was null, and <=> yielded comparison integers.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Configure Default Server Port

  • PointDeclare $customPort = null.
  • PointUse the null coalescing operator to assign $port = $customPort ?? 3000.
  • PointPrint "Server listening on port: [port]".
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates