PHP 8.x Quick Revision Notes
Exam-ready key points across all 51 PHP modules.
What is PHP? Request-Response Lifecycle, Zend Engine & PHP 8 Evolution
Understand how PHP executes on the server, the HTTP request-response lifecycle, Zend Engine internals, and PHP's evolution from PHP 3 to modern PHP 8.x.
- • **PHP 5**: Proper OOP model, PDO.
- • **PHP 7.x**: Massive 2x+ speed boost (Zend Engine 3), scalar type hints, return types, null coalescing `??`.
- • **PHP 8.0–8.4**: JIT compiler, Union/Intersection types, `match`, Attributes, Enums, `readonly` classes, Fibers, Property Hooks.
PHP CLI, Built-in Server, PHP-FPM, FastCGI & php.ini Configuration
Set up PHP on Windows/Linux/macOS, compare PHP CLI vs PHP-FPM/FastCGI web execution, and configure php.ini for development vs production.
- • **Stacks**: XAMPP (cross-platform), WAMP (Windows), LAMP (Linux), MAMP (macOS), or Docker.
- • **Built-in Dev Server**: Run `php -S localhost:8000 -t public/` for local development (never use in production!).
- • **CLI SAPI**: Executes scripts in terminal (`php script.php`), no HTTP headers, unlimited execution time by default.
PHP Tags, Lexer/Parser, Statements vs Expressions & Logic Separation
Master <?php tags, PHP lexical tokenization, statements vs expressions, comments, and clean separation of PHP logic from HTML templates.
- • **Best Practice**: Omit the closing `?>` tag in pure PHP files to prevent accidental trailing whitespace from triggering *"headers already sent"* errors!
- • **Expression**: Evaluates to a value (`$a + $b`, `match($x) { ... }`).
- • **Statement**: Performs an action ending with `;` (`if`, `echo`, `return`).
PHP Data Types, Type Juggling vs Strict Typing & Variable Storage
Explore all 8+ PHP types (int, float, string, bool, null, array, object, resource), zval internal storage, type juggling pitfalls, and strict_types=1.
- • **Scalar**: `int`, `float`, `string`, `bool`.
- • **Compound**: `array`, `object`, `callable`, `iterable`.
- • **Special**: `null`, `resource` (external handle like file/stream).
PHP Operators, == vs ===, Null Coalescing (?? / ??=) & Spaceship (<=>)
Master all PHP operators, why == vs === behave differently, null coalescing ?? and ??=, spaceship <=>, and operator precedence bugs.
- • **Null Coalescing (`??`, PHP 7.0)**: `$name = $_GET['name'] ?? 'Guest';` (checks `isset`, no undefined-key warning!).
- • **Null Coalescing Assignment (`??=`, PHP 7.4)**: `$config['port'] ??= 8080;`.
- • **Spaceship (`<=>`, PHP 7.0)**: Returns `-1`, `0`, or `1` (ideal for `usort`).
if/elseif, switch vs. PHP 8 match() Expression & Guard Clauses
Compare if/elseif/else, switch (loose ==), and PHP 8.0 match (strict ===, expression-based, no fall-through), plus flattening nested ifs with guard clauses.
- • | Loose (`==`) | **Strict (`===`)** |
- • | Yes (needs `break;`) | **No** (single arm executes) |
- • | No (statement) | **Yes (expression)** |
PHP Loops (for, while, do-while, foreach) & Iteration Performance
Master for, while, do-while, and foreach loops, break/continue with numeric levels, reference pitfalls in foreach, and iteration complexity.
- • **`foreach`**: Idiomatic choice for PHP arrays and `Traversable` objects (`foreach ($map as $key => $val)`).
- • **`for`**: Known numeric ranges (`for ($i = 0; $i < $n; $i++)`).
- • **`while` / `do-while`**: Unknown iteration counts (e.g., reading stream lines).
PHP Strings, Heredoc/Nowdoc, UTF-8 Multibyte (mb_*) & Context-Aware Escaping
Master string interpolation, heredoc/nowdoc, PHP 8 str_contains/str_starts_with, UTF-8 multibyte mb_strlen, and why escaping depends on output context.
- • **Single quotes (`'...'`)**: Literal, no variable interpolation.
- • **Nowdoc (`<<<'EOT'`)**: Multiline literal without interpolation.
PHP Ordered-Map Arrays, Copy-on-Write & Essential array_* Functions
Understand PHP arrays as hash-table ordered maps, Copy-on-Write memory semantics, destructuring, spread unpacking, and all core array_* functions.
- • **Functional**: `array_map`, `array_filter`, `array_reduce`, `array_walk`.
- • **Keys/Values/Columns**: `array_keys`, `array_values`, `array_column`, `array_flip`, `array_combine`.
- • **Search/Set/Slice**: `in_array($x, $arr, true)` (always pass `true` for strict!), `array_search`, `array_unique`, `array_merge`, `array_slice`, `array_splice`, `array_diff`, `array_intersect`.
PHP Functions, Type Contracts, Named Arguments (PHP 8.0) & Variadics
Master function call stack frames, parameter/return/nullable type declarations, PHP 8.0 named arguments, variadic ...$args, and pass-by-value vs reference.
- • **Named Arguments**: `createUser(name: "Aarav", isAdmin: true)` skips optional defaults cleanly.
- • **Variadics**: `function sum(int ...$nums): int` accepts any number of typed arguments.
Closures, Arrow Functions (PHP 7.4), First-Class Callables (PHP 8.1) & Functional PHP
Deep dive into Closure objects, lexical capture with use(), PHP 7.4 arrow functions fn(), PHP 8.1 first-class callable syntax strlen(...), and pure functions.
- • **Closure (`function () use ($x)`)**: Multi-line; requires explicit `use ($x)` (by value) or `use (&$x)` (by reference).
Variable Scope, Static Variables, References (&) & Avoiding Global State
Understand PHP function scope, static local variables, superglobal visibility, symbol-table aliases (&), and why global state harms testability.
- • **`static` local variables**: Retain their value across calls to the same function.
- • **Why avoid `global`**: Hidden dependencies make unit testing, concurrency, and refactoring brittle—use **dependency injection** instead!
Constants (define vs const), Class Constants & Magic Constants
Compare compile-time const vs runtime define(), typed class constants (PHP 8.3), and magic constants (__DIR__, __FILE__, __LINE__, __CLASS__).
- • **`const`**: Evaluated at **compile time**; respects namespaces and class visibility (`public const`, `private const`). Cannot be used inside `if` blocks.
- • **`define()`**: Evaluated at **runtime**; can be conditional.
Object-Oriented PHP: Classes, Encapsulation, Constructors & Object Lifecycle
Master PHP OOP fundamentals: classes vs objects, encapsulation, public/protected/private, __construct/__destruct, $this, static members, and __clone.
- • **`$this`**: Refers to the current object instance.
- • **`static` members**: Belong to the class itself (`self::$count`), not individual instances.
- • **Object Cloning**: `$b = clone $a;` performs a shallow copy; implement `__clone()` for deep copies of nested objects.
Inheritance, Abstract Classes, Interfaces, Traits & Late Static Binding
Master runtime polymorphism, abstract contracts vs interfaces, horizontal code reuse with Traits (insteadof/as), final classes, and static:: Late Static Binding.
- • **Abstract Class**: Partial implementation + shared state; single inheritance (`extends`).
- • **Interface**: Pure behavioral contract (`implements`); a class can implement multiple interfaces.
- • **Trait**: Horizontal code reuse (`use Timestampable;`); resolve method collisions with `insteadof` and `as`.
PHP 8 Type System: Union, Intersection, never, mixed & Variance
Master PHP 8.0 Union types, PHP 8.1 Intersection types (A&B) & never return type, PHP 8.2 DNF types, and LSP covariance/contravariance.
- • **Union Types (PHP 8.0)**: `int|float|string`
- • **Intersection Types (PHP 8.1)**: `Countable&Iterator` (object must satisfy *both* interfaces).
- • **`mixed` (PHP 8.0)**: Equivalent to `object|resource|array|string|int|float|bool|null`.
Modern PHP 8.0–8.4 Features: Enums, Attributes, Readonly, Nullsafe & Property Hooks
Explore version-by-version modern PHP features: 7.4 typed properties, 8.0 nullsafe ?-> & attributes, 8.1 backed enums & readonly, 8.2 readonly classes.
- • **PHP 7.4**: Typed properties, arrow functions `fn()`.
- • **PHP 8.0**: Constructor property promotion, `match`, named arguments, nullsafe `?->`, `#[Attributes]`.
- • **PHP 8.1**: Backed `enum`, `readonly` properties, Fibers, `never`.
Namespaces, spl_autoload_register() & PSR-4 Standard
Eliminate manual require_once spaghetti with PHP namespaces, use aliases, spl_autoload_register(), and PSR-4 folder conventions.
- • Eliminate manual require_once spaghetti with PHP namespaces, use aliases, spl_autoload_register(), and PSR-4 folder conventions.
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
Composer, composer.lock, Semantic Versioning & PSR-4 Autoloading
Manage PHP packages professionally with Composer: composer.json vs composer.lock, SemVer constraints (^1.2), install vs update, and dump-autoload.
- • **`composer install`**: Reads `composer.lock` and installs exact reproducible versions (always use in CI/production!).
- • **`composer update`**: Resolves newer versions matching `composer.json` constraints and rewrites `composer.lock`.
PHP Error Model, Throwable Hierarchy, Custom Exceptions & Production Logging
Master PHP's Throwable hierarchy (Error vs Exception), try/catch/finally, custom domain exceptions, and why display_errors must be Off in production.
- • Master PHP's Throwable hierarchy (Error vs Exception), try/catch/finally, custom domain exceptions, and why display_errors must be Off in production.
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
PHP Superglobals, HTTP Trust Boundaries & Input Filtering
Understand all 9 PHP superglobals ($_GET, $_POST, $_SERVER, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV, $GLOBALS) and never trust raw user input.
- • Understand all 9 PHP superglobals ($_GET, $_POST, $_SERVER, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV, $GLOBALS) and never trust raw user input.
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
Form Handling, Validation vs. Sanitization & CSRF Protection
Build secure PHP form handlers: GET vs POST, server-side validation, HTML escaping on redisplay, Post/Redirect/Get (PRG), and CSRF tokens.
- • **Validation**: Rejects invalid data (e.g., empty name, invalid email).
- • **Sanitization / Escaping**: Cleans or encodes data for output (`htmlspecialchars`).
- • **CSRF Protection**: Generate a cryptographically random token (`bin2hex(random_bytes(32))`) stored in `$_SESSION` and verify with `hash_equals()`.
HTTP Cookies, Secure Flags (HttpOnly, Secure, SameSite) & Lifecycle
Create, update, and delete cookies securely in PHP using Secure, HttpOnly, and SameSite options to defend against XSS theft and CSRF.
- • **`httponly => true`**: Blocks JavaScript `document.cookie` access (protects against XSS).
- • **`secure => true`**: Transmits cookie only over HTTPS.
PHP Sessions, Session Fixation Prevention & Secure Authentication Flow
Manage server-side state with PHP sessions, prevent session fixation via session_regenerate_id(true), handle timeouts, and destroy sessions cleanly.
- • **Prevent Session Fixation**: Always call `session_regenerate_id(true);` immediately after a successful login!
- • **Secure Logout**: Clear `$_SESSION = []`, expire the session cookie, and call `session_destroy()`.
File Handling, Locking (flock) & Secure File Upload Architecture
Read/write files safely, prevent race conditions with flock(), block path traversal (../), and validate uploaded files by MIME type and random filenames.
- • **Path Traversal Prevention**: Never pass raw `$_GET['file']` into `fopen()` or `include()`; use `basename()` and an allowlist!
- • **Upload Security**: Check `$_FILES['f']['error'] === UPLOAD_ERR_OK`, verify real MIME type with `finfo_file()`, generate a random UUID filename, and store uploads *outside* the public webroot.
PHP Streams, Wrappers (php://input, php://memory), Contexts & Filters
Process gigabyte files and HTTP/JSON payloads without exhausting RAM using PHP stream wrappers, contexts, and stream filters.
- • `php://input`: Reads raw JSON request bodies in REST APIs.
- • `php://memory` / `php://temp`: In-memory temporary streams.
Database Programming with PDO, Prepared Statements & SQL Injection Defense
Connect PHP to MySQL safely using PDO, understand how prepared statements separate SQL structure from bound parameters to prevent SQL Injection, and use transactions.
- • FROM users WHERE email = '$email'"`), an attacker can inject SQL syntax. **Prepared statements** send the SQL template to MySQL first, then bind parameters separately as pure data—making SQL injection impossible!
- • supports 12+ databases, named parameters (`:email`), and clean exception mode (`PDO::ERRMODE_EXCEPTION`), making it the modern standard.
Advanced PDO: Fetch Modes, Atomic Transactions & Repository Pattern
Master PDO fetch modes (FETCH_ASSOC, FETCH_CLASS, FETCH_KEY_PAIR), beginTransaction/commit/rollBack atomic workflows, and clean Repository abstraction.
- • Master PDO fetch modes (FETCH_ASSOC, FETCH_CLASS, FETCH_KEY_PAIR), beginTransaction/commit/rollBack atomic workflows, and clean Repository abstraction.
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
Relational Modeling, Indexing, Pagination & Solving the N+1 Query Problem
Design normalized MySQL schemas with foreign keys and B-Tree indexes, implement safe LIMIT/OFFSET or keyset pagination, and eliminate N+1 query bottlenecks.
- • FROM users WHERE id = ?` queries inside a `foreach` loop executes **101 queries**! Fix it with a `JOIN` or eager-loading `WHERE id IN (...)`.
Advanced PHP Security: Defense in Depth, XSS/SQLi/CSRF, IDOR & Security Headers
Master production PHP security: trust boundaries, password_hash/verify, htmlspecialchars, PDO prepared statements, CSRF tokens, IDOR authorization checks, and HTTP security headers.
- • **SQL Injection**: Always use PDO prepared statements with `ATTR_EMULATE_PREPARES => false`.
- • **XSS**: Encode HTML output with `htmlspecialchars($val, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')`.
- • **Passwords**: Never use MD5/SHA1/SHA256! Always use `password_hash($pw, PASSWORD_ARGON2ID)` (or `PASSWORD_BCRYPT`) and `password_verify()`.
Authentication Lifecycle, RBAC Permissions & Secure Remember-Me Architecture
Design secure registration/login flows, Role-Based Access Control (RBAC), permission matrices, and split-token remember-me authentication.
- • **Authentication (AuthN)**: Verifying *who* the user is.
- • **Authorization (AuthZ / RBAC)**: Verifying *what* permissions their role holds (`admin`, `instructor`, `student`). Always deny by default!
Building Production REST APIs in PHP: Routing, JSON Contracts & Status Codes
Design stateless REST APIs in PHP with proper HTTP verbs (GET/POST/PUT/PATCH/DELETE), status codes (200/201/400/401/404/422), JSON payloads, and API versioning.
- • Design stateless REST APIs in PHP with proper HTTP verbs (GET/POST/PUT/PATCH/DELETE), status codes (200/201/400/401/404/422), JSON payloads, and API versioning.
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
PHP MVC Architecture: Front Controller, Router, Services & Repositories
Structure scalable PHP apps using the Front Controller pattern (public/index.php), Router, Controllers, Services, Repositories, and Views.
- • **Front Controller (`public/index.php`)**: Single entry point routing all requests.
- • **Controller**: Parses HTTP input, delegates to **Services**, returns View/JSON. Keep controllers thin!
- • **Service Layer**: Business rules and transactions.
Design Patterns & SOLID Principles in Modern PHP
Master SOLID principles and key patterns in PHP: Factory, Strategy, Observer, Decorator, Repository, Dependency Injection, Service Container, and when to avoid Singletons.
- • and **Composition over Inheritance** (`Strategy`, `Decorator`, `Repository`) instead of global `Singleton` state, which hides dependencies and complicates PHPUnit testing.
Automated Testing with PHPUnit: Unit/Integration Tests, Mocks & TDD
Write deterministic unit and integration tests with PHPUnit, understand mocks vs stubs, test fixtures, and CI pipelines.
- • **Unit Tests**: Fast, isolated tests using **Stubs** (canned return values) and **Mocks** (verifying method interactions).
- • **Integration Tests**: Verify real PDO database queries and HTTP endpoints.
PHP Performance Optimization: OPcache, JIT, Memory & Profiling
Accelerate PHP applications with OPcache, understand PHP 8 JIT, optimize SQL/N+1 bottlenecks, use generators for memory, and profile before optimizing.
- • caches compiled Zend opcodes in shared memory, eliminating disk reads and parsing on every request (2x–5x speedup). Most real-world bottlenecks are **I/O (unindexed SQL queries, external HTTP)**—profile with Xdebug/Blackfire before micro-optimizing.
Scalable PHP Architecture: Modular Monolith, Layers, Queues & Microservices
Choose the right architecture for growth: Layered Architecture, Modular Monoliths, async background queues, and when microservices make sense.
- • (clear module boundaries, Service + Repository layers) and offload heavy tasks (emails, PDFs) to **background queues** (Redis/RabbitMQ workers) before splitting into microservices.
PHP CLI Scripting, Arguments ($argv), Exit Codes & Cron Automation
Build robust PHP CLI tools and scheduled cron jobs using $argv/$argc, getopt(), STDERR logging, and proper UNIX exit codes (0 vs non-zero).
- • Build robust PHP CLI tools and scheduled cron jobs using $argv/$argc, getopt(), STDERR logging, and proper UNIX exit codes (0 vs non-zero).
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
JSON Serialization in PHP: json_encode, json_decode, JsonSerializable & json_validate()
Serialize and parse JSON safely with JSON_THROW_ON_ERROR, associative mode, JsonSerializable interface, and PHP 8.3 json_validate().
- • Serialize and parse JSON safely with JSON_THROW_ON_ERROR, associative mode, JsonSerializable interface, and PHP 8.3 json_validate().
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
XML Parsing (SimpleXML & DOMDocument) and XXE Security Prevention
Parse and generate XML with SimpleXML and DOMDocument, and protect against XXE (XML External Entity) injection vulnerabilities.
- • file-disclosure attacks)—avoid passing `LIBXML_NOENT` on untrusted XML!
DateTimeImmutable, Time Zones (UTC) & DateInterval Calculations
Avoid subtle mutation bugs by using DateTimeImmutable over DateTime, store timestamps in UTC, and perform calendar arithmetic with DateInterval.
- • and convert to user timezone only at display.
PCRE Regular Expressions, Lookarounds & ReDoS Awareness
Master preg_match, preg_match_all, preg_replace, preg_split, capturing groups, greedy vs lazy quantifiers, lookahead/lookbehind, and ReDoS prevention.
- • backtracking on malformed input; prefer `filter_var()` for emails/URLs!
Iterators & Generators (yield): Lazy Evaluation & O(1) Memory Streaming
Process millions of records in constant O(1) memory using PHP Generators (yield), Iterator, and IteratorAggregate interfaces.
- • function using `yield` pauses execution and produces one value at a time in **O(1) memory**!
PHP 8 Attributes (#[Attribute]) & Runtime Reflection API
Declare structured metadata with PHP 8.0 Attributes and inspect classes, methods, and attributes dynamically using ReflectionClass.
- • Declare structured metadata with PHP 8.0 Attributes and inspect classes, methods, and attributes dynamically using ReflectionClass.
- • Practice writing and running standard examples.
- • Apply best practices and debugging techniques.
PHP 8.1 Fibers, Cooperative Multitasking & Async PHP Ecosystem
Understand PHP 8.1 Fibers (start, suspend, resume), cooperative multitasking vs OS threads, and why Fibers require an event loop (ReactPHP/AMPHP/Revolt) for non-blocking I/O.
- • (PHP 8.1) provide lightweight, full-stack interruptible functions (`Fiber::suspend()`, `$fiber->resume()`) for **cooperative multitasking**. Note: Fibers *alone* do not make blocking `PDO` or `sleep()` asynchronous—they power async event loops like **Revolt / AMPHP / ReactPHP**!
PHP Frameworks (Laravel, Symfony, CodeIgniter): Middleware, DI & ORM
Understand why PHP frameworks exist, framework vs library inversion of control, middleware pipelines, Service Containers, and comparing Laravel, Symfony, and CodeIgniter.
- • call; a framework calls *your* code (**Inversion of Control**). Modern frameworks (Laravel, Symfony, CodeIgniter) provide Routing, **Middleware pipelines**, **DI Service Containers**, Validation, and **ORM** (Eloquent / Doctrine).
Laravel Architecture: Request Lifecycle, Service Container, Blade & Eloquent
Learn Laravel's request lifecycle, Service Container & Providers, Routing, Controllers, Middleware, Blade templates, Migrations, and Eloquent ORM.
- • **Service Container**: Auto-resolves constructor dependencies via Reflection.
- • **Migrations**: Version-controlled database schema changes (`php artisan migrate`).
Production PHP Deployment: Nginx, PHP-FPM Workers, Secrets & Zero-Downtime
Deploy PHP reliably on Linux with Nginx + PHP-FPM worker tuning, .env secret isolation, file permissions, OPcache preloading, and atomic symlink rollbacks.
- • workers.
- • Keep `.env` and `vendor/` outside `public/` webroot.
- • Run `composer install --no-dev --optimize-autoloader`, set `display_errors = Off`, and deploy via atomic symlinks for instant rollbacks.
PHP Debugging Methodology: Stack Traces, Logs & Xdebug Step Debugging
Debug complex PHP bugs systematically using structured logs, exception stack traces, Xdebug breakpoints, and call-stack inspection.
- • (`xdebug.mode=debug`) in your IDE for live breakpoints, variable inspection, and stack traces, and log structured JSON context in production.
Modern PHP Best Practices: PSR-12, strict_types, SOLID, DRY & Clean Code
Write maintainable, review-ready PHP following PSR-12 formatting, strict_types=1, SOLID, DRY/KISS/YAGNI, static analysis (PHPStan/Psalm), and clean refactoring.
- • Follow **PSR-12** coding style and **PSR-4** autoloading.
- • Put `declare(strict_types=1);` in every file.
- • Run **PHPStan** or **Psalm** for static type analysis before code review.
Real-World PHP Projects: Architecture, Database Design & Implementation
Build progressively challenging PHP projects from Beginner CLI/Form apps to Intermediate Auth/CRUD systems and Advanced REST APIs, E-Commerce, and MVC platforms.
- • **Beginner**: CLI Calculator, Contact Form (CSRF + validation), To-Do List, Quiz App.
- • **Intermediate**: Auth System (`password_hash` + `session_regenerate_id`), Blog/Inventory CRUD with PDO Pagination.
- • **Advanced / Professional**: Versioned REST API, RBAC Admin Dashboard, E-Commerce Backend, Modular MVC / Laravel App.