Modern PHP, Zend Engine Internals & Scalable Web Architecture Master Interview Bank
Zend Engine architecture, zval memory layout, reference counting & GC, OPcache, JIT compiler, Fibers, SPL, streams, and PHP-FPM process tuning.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Core Language, Execution Lifecycle & Types (1 - 10)
10 QuestionsHow does the PHP Execution Lifecycle work (SAPI, FastCGI, and PHP-FPM)?
PHP does not run as a continuous in-memory application server by default. Instead, it follows a Share-Nothing Architecture where each incoming HTTP request executes in an isolated process/thread, initializes state, runs code, and completely destroys all memory on request termination.: Module Init (MINIT): Triggered once when PHP-FPM...
What are the major language features introduced in modern PHP 8.0 through 8.3?
Modern PHP is a strictly typed, high-performance object-oriented language.: PHP 8.0: JIT Compiler, Union Types, Attributes (annotations), Named Arguments, Match Expression, Constructor Property Promotion, Nullsafe.
Explain the PHP Type System: Union Types, Intersection Types, and DNF Types?
Union Types (AB): Accepts either type A or type B • Intersection Types (A&B): Accepts a value that must implement both type A and type B simultaneously • DNF Types ((A&B)C): Disjunctive Normal Form allows combining intersection types wrapped in unions.
What is Constructor Property Promotion in PHP 8+ and how does it reduce boilerplate?
Declares class visibility and types directly in the constructor arguments, automatically assigning them to class properties.
How does the Match Expression differ from the classic Switch Statement?
Strict Type Comparison: match uses identity checks (===), whereas switch uses loose coercion (==) • Returns a Value: match is an expression that returns a value directly • No Break Required: No fallthrough bugs; execution stops once a pattern matches.
What are PHP Attributes and how do they replace DocBlock annotations?
Attributes (#[Attribute]) provide native, structured, compile-time metadata on classes, methods, and properties. Unlike docblocks (/ @Route(...) /), attributes are first-class language constructs parsed by the Zend Engine rather than parsed through regex strings.
How does String handling work in PHP and what is the difference between single and double quotes?
Single Quotes ('text'): String is parsed as a pure literal • Double Quotes ("text"): Evaluates variable expressions ("Hello $name") and escape characters (\n, \t).
How do PHP Arrays work internally as ordered hash tables (zval buckets)?
A PHP array is not a simple C array; it is a HashTable that preserves insertion order. Each element is stored in a Bucket containing the hash, string key or integer index, and a zval representing the value.
What are Magic Methods in PHP and what are their performance impacts?
Magic methods (e.g., construct, get, set, call, invoke, clone) allow classes to intercept operations. However, get and call bypass OPcache direct property lookups, adding slight CPU overhead.
How does the Error and Throwable hierarchy work in modern PHP?
All exceptions and fatal errors implement the Throwable interface.: Exception: Base class for developer-handled application exceptions • Error: Base class for internal engine fatal errors (e.g., TypeError, ParseError, DivisionByZeroError), allowing fatal engine issues to be caught.
Part 2: Zend Engine Internals, OPcache & Memory Architecture (11 - 24)
14 QuestionsExplain the Zend VM architecture and the zval memory layout?
Every variable in PHP is represented by an internal C struct called zval (Zend Value). In PHP 7+, zval was redesigned down to 16 bytes. Simple types (integers, floats, booleans) are stored inline directly inside the 16-byte struct, avoiding secondary heap allocations.
How does Reference Counting and the Circular Reference Garbage Collector work in PHP?
Complex values (strings, arrays, objects) maintain a refcount field. When variable assignments point to an object, refcount increments; when variables go out of scope, it decrements. When refcount hits 0, memory is freed immediately. If object A references B and B references A, their refcounts never reach 0.
How does OPcache work and what are the best production configuration settings?
PHP compiles script files into opcodes (virtual machine instructions). Without OPcache, every HTTP request recompiles all PHP files from scratch. OPcache stores compiled opcodes in shared memory, allowing PHP to execute instructions directly with zero parsing overhead.
What is the PHP 8 JIT (Just-In-Time) Compiler and when does it improve performance?
The JIT Compiler compiles frequently executed opcodes into native x86/ARM CPU machine instructions.: CPU-Bound Code (Math, AI, 3D rendering, compression): 2x to 5x faster • Typical Web Apps (Laravel, WordPress): Negligible speedup because real-world web apps are I/O bound (database, network sockets, file reads), not.
What are PHP Fibers and how do they enable Cooperative Multitasking?
Fibers are lightweight, stackful coroutines that allow an execution stack to be paused (Fiber::suspend()) and resumed later ($fiber->resume()) without blocking the underlying thread. They form the foundation for asynchronous frameworks like Revolt, Amp, and Swoole.
How do Generators and the yield keyword enable memory-efficient streaming of large datasets?
Standard functions return a complete collection, loading millions of records into memory at once. A Generator yields values one at a time on demand, consuming a flat constant amount of memory (O(1) RAM).
What are SPL (Standard PHP Library) Data Structures and when should you use them over arrays?
PHP arrays are general-purpose ordered maps. SPL provides specialized data structures that consume less memory: SplFixedArray: Contiguous C array; uses 50% less RAM than a standard array • SplQueue / SplStack: Fast FIFO/LIFO operations with O(1) push/pop.
What is a WeakMap in PHP 8 and how does it prevent memory leaks in caching?
A WeakMap holds references to object keys without preventing the Garbage Collector from freeing them. When the object key is destroyed, its corresponding entry in the WeakMap is automatically removed.
How does Composer Autoloading and PSR-4 work under the hood?
PSR-4 maps namespace prefixes to relative directory paths. Composer generates an internal class map file (vendor/composer/autoload_classmap.php). In production, running composer dump-autoload -o creates an authoritative O(1) array lookup, eliminating filesystem lookups entirely.
What are PHP Streams and Stream Wrappers?
Streams generalize file, network, and data operations into a uniform interface (fopen('s3://bucket/key'), fopen('php://memory')). Custom Stream Wrappers allow applications to transparently read/write to custom cloud protocols without altering code.
How does PHP handle Cryptography using the libsodium extension?
PHP 7.2+ bundles libsodium as the core cryptographic engine. It provides modern primitives that are resilient against timing attacks (sodiumcryptosecretbox, sodiumcryptopwhash using Argon2id).
What are Readonly Classes and Properties and what guarantees do they provide?
A readonly property can only be initialized once within its declared scope and can never be mutated afterward. Declaring readonly class enforces immutability across all instance properties.
What is the First-Class Callable Syntax in PHP 8.1+?
Using this->method(...) creates an anonymous Closure object referencing the callable directly, replacing fragile string/array callables like [this, 'method'].
How does Session Locking in PHP-FPM affect concurrent user requests?
When sessionstart() is invoked, PHP locks the session file on disk. Any subsequent concurrent AJAX requests from the same user stall until the first request completes or calls sessionwrite_close().
Part 3: Production Tuning, Asynchronous Workers & High Scale (25 - 35)
26 QuestionsHow do you correctly configure and tune PHP-FPM process managers (static vs dynamic)?
For high-traffic production environments with dedicated RAM, use pm = static to avoid the process spawning/destroying overhead of dynamic.
How do you detect and diagnose memory leaks in long-running PHP CLI workers?
Because PHP was designed to discard memory after each web request, long-running CLI daemons (queue workers) frequently suffer from memory leaks caused by unbounded static collections and event listener registrations.: Track usage with memorygetusage(true) • Regularly cycle worker processes after processing N jobs.
What is OPcache Preloading and how does it optimize enterprise framework startup?
Introduced in PHP 7.4, OPcache Preloading compiles specified PHP files into memory once on server startup and keeps all their classes and functions permanently available to all requests without ever calling require or include.
How do you write performant asynchronous microservices in PHP using Swoole or RoadRunner?
Application servers like RoadRunner (written in Go) or Swoole (C++ extension) run PHP as a persistent in-memory process, bypassing the PHP-FPM bootstrap cycle and delivering 10,000+ requests per second.
What are Weak References vs Weak Maps in PHP and how do they assist garbage collection?
WeakReference allows a program to retain a reference to an object that does not prevent that object from being garbage-collected, critical for memory caches.
How do you profile PHP performance in production using Tideways or Blackfire?
Never run Xdebug in production (causes a 200%+ slowdown). Use Blackfire or Tideways which use lightweight statistical sampling to generate execution call graphs and pinpoint wall-clock bottlenecks.
How do you safely handle large file uploads without running out of RAM in PHP?
Never read uploaded files using filegetcontents(). Stream bytes chunk-by-chunk using fopen('php://input', 'rb') directly to cloud storage (e.g., S3 multipart upload).
What is Copy-On-Write (COW) in PHP memory management?
When an array is assigned to another variable (b = a), PHP does not allocate new memory. Both variables point to the same internal array struct. A duplicate copy is allocated only when one of the variables is modified.
How do you implement graceful shutdown in PHP queue consumers?
Listen for POSIX signals (SIGTERM, SIGINT) using pcntl_signal(). When received, allow the currently running job to finish before exiting cleanly.
How does the PHP Garbage Collector manage root buffers to avoid memory spikes?
The GC root buffer tracks up to 10,000 suspect objects. When full, it performs a color-marking cycle (Purple, Grey, Black, White) to detect references that only point to each other.
When should you choose Modern PHP over Node.js, Python, or Go for backend services?
Choose Modern PHP for web applications requiring rapid business logic iteration, enterprise ORM capabilities, strict typing, and rock-solid request isolation with near-zero memory leak risk.
Modern PHP Features (PHP 8.1 - 8.4): Enums, Readonly Classes, and Property Hooks.
Modern PHP has evolved into a strictly typed, expressive object-oriented language: Backed Enums (PHP 8.1): Typed enumerations with scalar values (enum Status: string { case Active = 'A'; }) that can implement interfaces and.
PHP Advanced Type System: Union Types, Intersection Types, and DNF Types.
Union Types (T1 T2): Accepts either Type 1 or Type 2 (intfloat) • Intersection Types (T1 & T2): Value must satisfy both interfaces simultaneously (Countable & Iterator) • Disjunctive Normal Form (DNF Types - PHP 8.2+): Combines unions and intersections with parentheses: (HasTitle & HasAuthor) null.
PHP Fibers: Cooperative Multitasking and Asynchronous I/O.
Fibers (PHP 8.1+) provide low-level primitives for coroutine concurrency: A Fiber is an interruptible execution block that can pause itself using Fiber::suspend() and resume execution later with Fiber::resume().
PHP-FPM (FastCGI Process Manager) Architecture and Tuning.
PHP-FPM runs a master process that manages worker pools to execute PHP scripts: Share-Nothing Architecture: Each HTTP request is handled by an isolated worker process • Process Manager Modes • static: Fixed number of workers running continuously.
OPcache, Preloading, and the PHP JIT Compiler.
OPcache: Caches compiled PHP opcode in shared RAM, eliminating the need to parse and compile PHP source files on every request • OPcache Preloading (opcache.preload): Compiles framework classes (e.g. Laravel or Symfony core) into shared memory on server startup, making.
PHP Garbage Collection and Memory Management.
PHP uses Reference Counting with a Cyclic Garbage Collector: Every variable container (zval) has a reference counter (refcount) • Circular Reference Collector: Objects pointing to each other (a->b = b; b->a = a;) prevent refcount from reaching zero.
PHP Magic Methods: Metaprogramming and Object Lifecycles.
Magic methods start with and intercept object behaviors: get(name) / set(name, $val): Intercepts access to inaccessible/undefined properties (powers dynamic ORM models) • call(name, args): Intercepts calls to undefined methods • __invoke(): Allows an object instance to be called directly as a function.
PHP 8 Native Attributes vs Legacy PHPDoc Annotations.
Prior to PHP 8, frameworks relied on parsing unstructured docblock comments (/ @Route("/api") /) via reflection strings.: Native Attributes (#[Route("/api")]): First-class structured metadata evaluated by the PHP compiler.
Weak References and `WeakMap` in PHP.
WeakReference: Allows referencing an object without increasing its refcount • WeakMap: A map where keys are objects.
Modern Dependency Injection and PSR-11.
PSR-11 (ContainerInterface): Standardizes how Dependency Injection containers fetch objects ($container->get('service')) • Autowiring: Uses Reflection to inspect class constructor type-hints and automatically resolves and instantiates dependency graphs recursively.
Core PHP-FIG PSR Standards.
The PHP Framework Interoperability Group (PHP-FIG) standardizes enterprise development: PSR-4: Autoloading standard mapping namespace paths directly to directory structures • PSR-7 & PSR-15: Standardizes HTTP message objects (ServerRequestInterface, ResponseInterface) and HTTP middleware pipelines.
Long-Running Application Servers: RoadRunner and Swoole.
Traditional PHP boots the framework on every HTTP request and dies. Long-running servers keep the framework in memory: RoadRunner (Go-based worker manager): Spawns persistent PHP worker processes communicating via binary IPC.
Security in Modern PHP: Password Hashing and Input Sanitization.
Password Hashing API: Always use passwordhash($pwd, PASSWORDARGON2ID) • Prepared Statements with PDO: Always use PDO::prepare() with parameter placeholders to eliminate SQL injection • Session Security: Set session.cookiehttponly = 1, session.cookiesecure = 1, and session.cookie_samesite = 'Strict'.
Error Hierarchy: `Throwable`, `Error`, and `Exception`.
Since PHP 7, fatal engine errors no longer crash the process abruptly: All errors and exceptions implement the Throwable interface • Error: Engine-level failures (TypeError, ParseError, DivisionByZeroError) • Exception: Application-level domain exceptions (DatabaseException, ValidationException).
Performance Profiling: Blackfire.io and Xdebug.
Xdebug: Indispensable for local step-debugging and code coverage, but introduces up to 200% overhead; never enable in production! • Blackfire.io: Production-safe profiler that measures exact CPU time, memory allocations, I/O waits, and SQL query counts across function call.