144 PHP Interview Questions and Answers (2026)

Blog / 144 PHP Interview Questions and Answers (2026)
PHP

PHP still runs a massive share of the web, and modern PHP 8.x is a different beast—typed, fast, JIT-powered, and powering everything from Laravel and Symfony apps to WordPress and high-traffic APIs. Interviewers know this, and they now expect real fluency, not memorized buzzwords. Walk in shaky on enums, attributes, or readonly classes and someone sharper takes the offer.

This guide gives you 144 questions with tight, interview-ready answers—code included where it actually helps. They're worked Junior → Mid → Senior, so you start with fundamentals and climb into design patterns, concurrency, opcache, and internals. Drill them in order, and you'll explain the why, not just the what.

Q1.
What are Enums in PHP 8.1, and why are they preferred over class constants for defining fixed sets of values?

Junior

Enums (PHP 8.1) are a dedicated type for a fixed, finite set of named values, replacing loose class constants with a real type the engine and IDE can validate.

  • Two kinds:

    • Pure enums: cases with no scalar value (enum Suit { case Hearts; }).

    • Backed enums: each case maps to an int or string (enum Status: string { case Active = 'active'; }), with from() and tryFrom() helpers.

  • Why preferred over class constants:

    • Type safety: you can type-hint Status $s, so only valid cases are accepted; a bare const lets any matching string slip through.

    • Each case is a singleton object, so identity comparison with === is reliable.

    • They can hold methods, implement interfaces, and use traits, keeping related behavior with the values.

    • cases() gives the full list for iteration/validation.

  • Caveat: Enums cannot have mutable state and cannot be instantiated with new.

php

enum Status: string { case Active = 'active'; case Banned = 'banned'; public function label(): string { return ucfirst($this->value); } } function setStatus(Status $s): void {} // only valid cases accepted Status::tryFrom('active'); // Status::Active or null

Q2.
Explain the MVC (Model-View-Controller) pattern as implemented in Laravel.

Junior

MVC separates an application into three responsibilities: Models handle data and business rules, Views render output, and Controllers coordinate between them. Laravel implements this with Eloquent models, Blade views, and controller classes wired together by routing.

  • Model: Usually an Eloquent class mapping to a table; holds data access, relationships, and domain logic.

  • View: Blade templates (.blade.php) that render HTML from data passed in; no business logic.

  • Controller:

    • Receives the request, calls models/services, and returns a response or view.

    • Kept thin: heavy logic belongs in models or service classes.

  • The flow:

    1. A route in routes/web.php maps a URL to a controller method.

    2. The controller queries a model and passes data to a view.

    3. The view renders and the response goes back to the browser.

php

// routes/web.php Route::get('/users', [UserController::class, 'index']); // Controller public function index() { $users = User::all(); // Model return view('users.index', compact('users')); // View }

Q3.
What is the difference between a session and a cookie in terms of storage location and security, and why shouldn't you store sensitive data in a cookie?

Junior

A cookie is stored on the client (the browser) and sent with every request, while a session stores data on the server and uses only a small session ID cookie to link the client to it. Because cookies live on the user's machine and travel over the network, they are easy to read or tamper with, so sensitive data belongs server-side in the session.

  • Storage location:

    • Cookie: stored in the browser, sent in the Cookie header on each request to that domain.

    • Session: data kept on the server (files, Redis, DB); the browser only holds the PHPSESSID identifier.

  • Security implications:

    • Cookies are user-controlled: readable, editable, and forgeable unless signed/encrypted.

    • Cookies are exposed to JavaScript (XSS) unless HttpOnly, and to network sniffing unless Secure.

    • Session data never leaves the server, so it can't be tampered with directly.

  • Why not store sensitive data in a cookie:

    • A cookie holding a role like is_admin=1 can simply be edited by the user.

    • Store an opaque session ID in the cookie and keep the real data (user ID, permissions) server-side.

Q4.
What is the current best practice for hashing passwords in PHP, and why are md5() or sha1() no longer acceptable?

Junior

The current best practice is to use PHP's built-in password_hash() with PASSWORD_DEFAULT (currently bcrypt, with Argon2 available) and verify with password_verify(). These use slow, salted, adaptive algorithms designed specifically for passwords, unlike fast general-purpose hashes.

  • Why password_hash() is right:

    • Generates a unique random salt automatically and embeds it in the output (no separate salt column needed).

    • Adaptive cost: you can raise the work factor as hardware improves.

    • password_needs_rehash() lets you upgrade old hashes transparently on login.

  • Why md5() and sha1() are unacceptable:

    • They are extremely fast, so attackers can compute billions of guesses per second (brute force / GPU cracking).

    • No built-in salting, making rainbow-table attacks trivial.

    • Both have known collision weaknesses and were never designed for password storage.

php

$hash = password_hash($password, PASSWORD_DEFAULT); if (password_verify($input, $hash)) { if (password_needs_rehash($hash, PASSWORD_DEFAULT)) { $hash = password_hash($input, PASSWORD_DEFAULT); // upgrade } }

Q5.
What is the difference between a Session and a Cookie in PHP? How does PHP track a session across multiple requests?

Junior

A cookie is a small piece of data stored in the browser and sent with each request; a session is server-side storage for user data. PHP links them by storing only a session ID in a cookie and keeping the actual data on the server.

  • Cookie: client-side: Stored in the browser, sent on every request to the domain; visible and editable by the user, so never trust it for sensitive data.

  • Session: server-side: Data lives on the server (files, Redis, DB); the client only holds an opaque identifier.

  • How tracking works:

    1. session_start() generates a session ID and sends it in the PHPSESSID cookie.

    2. On each later request the browser returns that cookie, and PHP loads the matching $_SESSION data.

  • Security notes: Use HttpOnly, Secure, and SameSite flags, and call session_regenerate_id() after login to prevent fixation.

Q6.
What is SQL Injection, and why are Prepared Statements (PDO/MySQLi) the standard way to prevent it?

Junior

SQL Injection is the injection of malicious SQL through unsanitized user input that alters a query's intended logic; prepared statements stop it by separating the query structure from the data so input can never be executed as code.

  • What it is: An attacker crafts input that breaks out of a string and adds clauses, enabling data theft, bypassed auth, or destructive commands like DROP TABLE.

  • Why prepared statements are the standard:

    • The query template is parsed first; bound parameters are then supplied as pure data, so structure can't change.

    • They work uniformly for all value types and remove the need for fragile manual escaping.

  • Named vs positional placeholders: PDO supports both :name and ? placeholders; pick one per query for clarity.

  • Defense in depth: Still validate input, use least-privilege DB accounts, and whitelist anything that can't be bound (column/table names).

php

$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute(['id' => $userId]); $user = $stmt->fetch();

Q7.
Why should you never use md5() or sha1() for password hashing, and what is the recommended alternative in modern PHP?

Junior

You should never use md5() or sha1() for passwords because they are extremely fast and were built for integrity, not secrecy; the modern alternative is PHP's password hashing API (password_hash() / password_verify()).

  • The problem with fast hashes:

    • Speed is a liability for passwords: attackers can brute-force or use precomputed rainbow tables against billions of candidates per second.

    • They have no built-in salt and known collisions, making them unfit even with manual salting.

  • The recommended approach:

    • password_hash() defaults to bcrypt (with PASSWORD_ARGON2ID available), automatically salting and applying a configurable work factor.

    • Verify with password_verify(), which reads the salt and cost from the stored hash itself.

  • Future-proofing: Use password_needs_rehash() on login to transparently upgrade hashes when you raise the cost or change the algorithm.

Q8.
What are the differences between public, protected, and private visibility, and how does protected behave differently in the context of inheritance?

Junior

Visibility controls where a property or method can be accessed: public everywhere, protected within the class and its subclasses, and private only within the declaring class itself.

  • public: Accessible from anywhere: outside code, subclasses, and the class itself.

  • protected: Accessible inside the declaring class and any class that extends it, but not from outside.

  • private: Accessible only within the exact class that declared it, not even in subclasses.

  • Inheritance distinction:

    • A private member is invisible to children, so a subclass can declare its own member of the same name without conflict.

    • A protected member is shared and overridable down the hierarchy, making it the right choice for internal state subclasses must reach.

Q9.
What is the difference between an Object and a Class?

Junior

A class is the blueprint or template that defines properties and methods, while an object is a concrete instance of that class created in memory with its own data.

  • Class: A definition written once with class; describes structure and behavior but holds no live data by itself.

  • Object:

    • A runtime instance created with new; each has its own property values and a unique identity.

    • Many objects can be instantiated from one class, each independent.

  • Analogy: the class is the cookie cutter, the objects are the individual cookies.

php

class Car { public string $color; } $a = new Car(); $a->color = 'red'; $b = new Car(); $b->color = 'blue'; // Car is the class; $a and $b are distinct objects

Q10.
How does Inheritance work in PHP, and what are its limitations?

Junior

Inheritance lets a child class extend a parent with extends, reusing and optionally overriding its non-private members. PHP supports only single inheritance, which is its main structural limitation.

  • How it works:

    • The child inherits all public and protected members and can override methods by redeclaring them.

    • Use parent:: to call the overridden parent implementation.

  • Limitations:

    • Single inheritance only: a class cannot extend more than one parent.

    • private members are not visible to children.

    • Deep hierarchies create tight coupling and fragile base classes.

  • Workarounds: use interfaces for multiple contracts and traits for horizontal code reuse; often prefer composition over inheritance.

Q11.
What are standard array functions like array_map and array_filter, and how do they differ in purpose?

Junior

Both are higher-order array functions, but they serve different purposes: array_map transforms every element, while array_filter selects a subset based on a predicate.

  • array_map:

    • Applies a callback to each element and returns a new array of the same length with transformed values.

    • Can iterate multiple arrays in parallel.

  • array_filter:

    • Keeps only elements for which the callback returns truthy, preserving original keys.

    • With no callback it removes falsy values.

  • Related: array_reduce collapses an array to a single value.

  • Note: array_filter preserves keys (you may need array_values to reindex), whereas array_map reindexes when mapping a single array.

php

$nums = [1, 2, 3, 4]; array_map(fn($n) => $n * 2, $nums); // [2, 4, 6, 8] array_filter($nums, fn($n) => $n % 2 === 0); // [1 => 2, 3 => 4]

Q12.
What is 'Object-Driven Programming' in the context of PHP development?

Junior

"Object-Driven" (more correctly Object-Oriented) Programming is a paradigm where the application is modeled as interacting objects that bundle data (properties) and behavior (methods) together, rather than as procedural sequences of functions.

  • Core idea: State and the operations on it live in the same unit (the object), promoting modularity.

  • Four pillars:

    • Encapsulation: hide internal state behind visibility and accessors.

    • Inheritance: derive specialized classes from a base.

    • Polymorphism: different classes respond to the same method call in their own way.

    • Abstraction: expose intent through interfaces and abstract types, hiding detail.

  • In PHP: built on class, interface, trait, and namespaces; underpins modern frameworks and the autoloading/dependency-injection ecosystem.

Q13.
What is the difference between a static method and an instance method, and when would you use a static method?

Junior

An instance method operates on a specific object via $this and is called on an instance, while a static method belongs to the class itself, is declared with static, and is called without an object. Use static methods for behavior that needs no instance state.

  • Instance method: Accesses per-object data through $this; called as $obj->method().

  • Static method: Called as ClassName::method(); has no $this and cannot touch instance state.

  • When to use static:

    • Utility/helper functions, factory or named constructors, and counters or other class-level data.

    • Use static:: inside for late static binding so subclasses resolve correctly.

  • Caution: static methods are harder to mock and can hide global state, so avoid them for behavior that should be testable or polymorphic.

Q14.
How does Composer handle dependency versioning, and what is the difference between composer.json and composer.lock?

Junior

Composer resolves dependencies from the version constraints in composer.json, picks the best compatible versions, and freezes that exact resolution in composer.lock for reproducible installs.

  • Versioning with semantic constraints:

    • ^1.2: allows updates that don't change the leftmost non-zero digit (1.2 up to but not including 2.0).

    • ~1.2: allows the last specified digit to increase (1.2 up to but not 2.0; ~1.2.3 up to 1.3).

    • Exact (1.2.3) or wildcards (1.2.*) are also supported.

  • composer.json vs composer.lock:

    • composer.json is the intent: which packages and what ranges are acceptable.

    • composer.lock is the result: the exact versions installed, so teammates and servers get the same builds.

  • Workflow: composer install honors the lock file; composer update re-evaluates constraints and refreshes the lock.

Q15.
What are PSR (PHP Standard Recommendation) standards, and why is PSR-4 specifically important for modern application structure?

Junior

PSRs are interoperability standards published by the PHP-FIG (Framework Interop Group) so code from different vendors works together; PSR-4 is the autoloading standard that maps namespaces to file paths, making manual require statements obsolete.

  • What PSRs are:

    • Recommendations, not language rules: they cover coding style (PSR-12), autoloading (PSR-4), logging (PSR-3), HTTP messages (PSR-7), and more.

    • Goal is interoperability: a library following the standards drops into any compliant project.

  • Why PSR-4 matters:

    • It defines a deterministic mapping: a fully-qualified class name maps to a directory + file, e.g. App\Service\Mailersrc/Service/Mailer.php.

    • Composer reads the autoload section and generates an autoloader, so classes load on demand with no manual includes.

    • This is what makes modern app structure (and the whole package ecosystem) work consistently.

json

{ "autoload": { "psr-4": { "App\\": "src/" } } }

Q16.
What are namespaces in PHP, and what problem do they solve?

Junior

Namespaces are a way to encapsulate and group related classes, functions, and constants under a named scope, solving the problem of name collisions between code from different sources.

  • The problem they solve:

    • Without namespaces, two libraries each defining a Logger class would fatally collide.

    • They also let you avoid absurdly long prefixed names like MyApp_Db_Connection.

  • How they work:

    • Declared with namespace App\Service; at the top of a file.

    • You import names with use, optionally aliasing with as to resolve clashes.

    • A leading \ denotes the global namespace (e.g. \strlen()).

  • They pair directly with PSR-4 autoloading, mapping namespace to directory.

php

namespace App\Service; use Monolog\Logger as MonoLogger; class Logger {} // App\Service\Logger, no clash

Q17.
What is the difference between == and === in PHP?

Junior

Both compare equality, but == compares values after type coercion, while === requires both the value and the type to match with no conversion.

  • == (loose): Juggles types before comparing, so 0 == "0" and 1 == true are both true.

  • === (strict): No conversion: 0 === "0" is false because int and string differ.

  • Rule of thumb: prefer === by default to avoid surprises from coercion.

Q18.
What is the difference between echo and print, and why is echo generally preferred in high-performance applications?

Junior

Both output strings, but echo is a language construct that can take multiple arguments and returns nothing, while print behaves like a function that returns 1; echo is marginally faster because it has no return value to manage.

  • echo:

    • Accepts multiple comma-separated arguments: echo $a, $b;.

    • Returns no value, so it can't be used in an expression.

  • print: Takes exactly one argument and returns 1, so it can sit inside expressions like $x = print "hi";.

  • Performance:

    • The difference is negligible in practice; the slight edge for echo comes from not allocating/returning a value.

    • Real-world output cost is dominated by I/O, not the choice between the two.

Q19.
Explain the difference between == (loose equality) and === (strict equality) in the context of PHP's type juggling.

Junior

== applies type juggling, converting operands to a comparable type before checking equality, whereas === compares value and type directly with no conversion.

  • How == juggles types:

    • If types differ, PHP converts one (often to number) then compares: "10" == 10 is true.

    • PHP 8 made this saner: comparing a number to a non-numeric string now compares as strings, so 0 == "abc" is false (it was true pre-8).

  • How === avoids it: Different types are immediately unequal: "10" === 10 is false.

  • Practical guidance: Default to ===; reserve == for cases where you deliberately want coercion and understand the rules.

Q20.
What is the difference between passing a variable by value and by reference in PHP?

Junior

By value (the default) passes a copy, so changes inside a function don't affect the caller; by reference passes an alias to the same variable, so changes propagate back.

  • By value (default):

    • The function gets its own copy; mutating it leaves the original untouched.

    • PHP uses copy-on-write internally, so a copy isn't physically duplicated until it's modified.

  • By reference (using &):

    • Prefix the parameter with & so the parameter and argument point to the same value.

    • Reassigning or mutating it inside the function changes the caller's variable.

  • Objects are a special case: Even passed by value, an object variable holds a handle, so mutating the object's properties affects the original; only reassigning the variable to a new object differs.

php

function addOne($x) { $x++; } // by value function addOneRef(&$x) { $x++; } // by reference $n = 5; addOne($n); // $n is still 5 addOneRef($n); // $n is now 6

Q21.
What are the main scalar and compound data types in PHP, and how does PHP handle type conversion between them?

Junior

PHP has four scalar types (int, float, string, bool) and compound types (array, object, callable, iterable), plus the special types null and resource; it converts between them automatically (juggling) based on context.

  • Scalar types: Hold a single value: int, float, string, and bool.

  • Compound types: Hold multiple values or structures: array and object (with callable and iterable as pseudo-types).

  • Type juggling (implicit conversion): In an arithmetic context a numeric string becomes a number; in a boolean context 0, "", "0", null, and empty arrays are falsy.

  • Explicit casting: Force a type with casts like (int), (string), (bool), or functions like intval() and settype().

  • Comparison caveat: Use === to avoid surprising loose-comparison juggling; == converts types before comparing.

Q22.
What is the difference between an indexed array, an associative array, and a multidimensional array in PHP?

Junior

They're all the same underlying array type in PHP: an indexed array uses integer keys, an associative array uses named (string) keys, and a multidimensional array nests arrays as values.

  • Indexed array: Auto-numbered integer keys starting at 0: ['a', 'b', 'c'].

  • Associative array: Explicit string keys mapping to values: ['name' => 'Ann', 'age' => 30].

  • Multidimensional array: Values are themselves arrays, forming nested tables or trees, accessed with chained keys like $data[0]['name'].

  • Key point: PHP arrays are ordered maps, so a single array can mix integer and string keys; the distinction is conceptual, not a separate type.

php

$indexed = ['red', 'green']; $assoc = ['r' => 255, 'g' => 128]; $matrix = [ ['name' => 'Ann', 'age' => 30], ['name' => 'Bob', 'age' => 25], ]; echo $matrix[1]['name']; // Bob

Q23.
What is the difference between isset(), empty(), and is_null()?

Junior

All three test variables but answer different questions: isset() asks "does it exist and is it non-null?", empty() asks "is it falsy (or missing)?", and is_null() asks "is it exactly null?".

  • isset(): Returns true if the variable is declared and not null; safe on undefined variables/array keys without a warning.

  • empty(): Returns true for any falsy value: 0, "", "0", null, false, empty array, and undefined variables.

  • is_null(): Returns true only when the value is exactly null; warns if the variable was never defined (it's a normal function, not a language construct).

  • Practical gotcha: A variable holding 0 is isset() true but empty() true too, so don't use empty() when 0 is a valid value.

Q24.
What is variable scope in PHP, and how does the 'global' keyword and the $GLOBALS array work?

Junior

Variable scope defines where a variable is accessible; PHP function bodies have their own local scope and do not see outer variables unless you import them with the global keyword or access them through the $GLOBALS superglobal array.

  • Local scope: Variables defined inside a function exist only there and vanish when it returns.

  • Global scope: Variables defined outside functions; unlike many languages, they are NOT automatically visible inside functions.

  • The global keyword: Declaring global $x; inside a function creates a local reference to the global $x so changes affect it.

  • The $GLOBALS array: A superglobal mapping global variable names to values: $GLOBALS['x'] reaches the same variable without a global declaration.

  • Best practice: Prefer passing values as parameters and returning results over globals, which create hidden coupling and make testing harder.

php

$count = 0; function increment() { global $count; // import the global $count++; // equivalent: $GLOBALS['count']++; } increment(); echo $count; // 1

Q25.
What is the difference between a constant defined with define() and one defined with const?

Junior

Both create constants, but const is a compile-time language construct defined at the top level or in classes, while define() is a runtime function that can be called conditionally and build names dynamically.

  • const:

    • Resolved at compile time, so it can't be used inside conditionals or loops.

    • The only way to define class constants: class A { const VERSION = 1; }.

    • Name must be a literal identifier, not a computed string.

  • define():

    • Runs at runtime, so you can call it inside if blocks or define the name from a variable.

    • Was needed for case-insensitive constants (third argument, now removed in PHP 8).

    • Cannot define class constants.

  • Shared traits: Both create immutable values; check existence with defined().

php

const MAX = 100; // compile time, top level define('MIN', 1); // runtime if ($debug) { define('LOG_LEVEL', 'verbose'); // conditional: const can't do this }

Q26.
How do default parameter values and variadic functions (using ...) work in PHP?

Junior

Default parameter values let a caller omit trailing arguments by giving them a fallback in the signature, while variadic functions use ... to collect any number of extra arguments into an array (or to spread an array into arguments).

  • Default parameter values:

    • Assigned in the signature: function f($x, $y = 10); omitting $y uses 10.

    • Defaults must be constant expressions and should come after required parameters.

  • Variadic parameter (...$args):

    • Captures remaining arguments as an array; must be the last parameter.

    • Can be type-hinted: function sum(int ...$nums) requires all extras to be ints.

  • Spread operator: The same ... at the call site unpacks an array into individual arguments: sum(...[1, 2, 3]).

php

function greet($name, $greeting = 'Hello') { return "$greeting, $name"; } greet('Ann'); // "Hello, Ann" function sum(int ...$nums) { return array_sum($nums); } sum(1, 2, 3); // 6 sum(...[4, 5, 6]); // 15 (spread)

Q27.
Explain the difference between include, require, include_once, and require_once.

Junior

All four pull another PHP file's contents into the current script; they differ in how they handle failure (require vs include) and whether they guard against loading the same file twice (the _once variants).

  • require vs include: failure behavior:

    • require: a missing file is a fatal error (E_COMPILE_ERROR) that halts the script.

    • include: a missing file is only a warning (E_WARNING) and execution continues.

  • The _once variants: duplicate protection:

    • require_once / include_once track loaded files and skip a second load of the same path.

    • Prevents fatal "cannot redeclare" errors from re-defining functions or classes.

  • Rule of thumb:

    • Use require for files the app can't run without; include for optional ones.

    • In modern projects, prefer Composer autoloading over manual require_once for classes.

Q28.
Explain the difference between GET and POST methods in the context of PHP superglobals.

Junior

GET and POST are HTTP methods that PHP exposes through the superglobals $_GET and $_POST: GET data travels in the URL query string, while POST data travels in the request body.

  • GET via $_GET:

    • Parameters appear in the URL (?id=5&page=2), so they are visible, bookmarkable, and logged.

    • Length-limited and meant for idempotent, read-only requests (searches, filters, pagination).

  • POST via $_POST:

    • Data is in the request body, not the URL, so it is not bookmarkable and supports larger payloads and file uploads.

    • Used for state-changing actions (create, update, login submissions).

  • Security caveat: POST is not encrypted by itself: only HTTPS protects either method. Both $_GET and $_POST are untrusted input and must be validated/sanitized.

Q29.
What is the functional difference between include and require, and when would you use require_once over require?

Junior

Both include and require pull another file into the current script; the difference is failure handling: a missing require is fatal, a missing include only warns.

  • include: On failure emits an E_WARNING and the script keeps running. Use for optional pieces (a sidebar, a template fragment).

  • require: On failure emits an E_ERROR and halts execution. Use for essential dependencies (config, core class, bootstrap).

  • require_once over require:

    • It guarantees the file is included only once per request, preventing fatal errors from redeclaring functions or classes.

    • Prefer it for files defining functions/classes; plain require is fine for templates you intentionally include repeatedly.

Q30.
What are superglobals in PHP? Can you name three and explain their specific use cases?

Junior

Superglobals are built-in PHP variables that are automatically available in every scope (no global keyword needed), holding request, server, and session data.

  • $_GET: Holds URL query-string parameters: read filters, pagination, search terms.

  • $_POST: Holds form-body data from POST submissions: logins, record creation, file metadata.

  • $_SESSION: Persists per-user data across requests (logged-in user id, cart) once session_start() is called.

  • Others worth knowing: $_SERVER (headers, paths, request method), $_COOKIE, $_FILES, $_ENV, and $_REQUEST.

Q31.
What is the difference between include, require, include_once, and require_once in terms of execution flow?

Junior

All four pull in another file at runtime, but they differ in two axes: how they react to a missing/failed file (include vs require) and whether the file is loaded more than once (the _once variants).

  • Failure behavior:

    • include: on failure emits an E_WARNING and the script continues executing.

    • require: on failure emits an E_COMPILE_ERROR (fatal) and halts the script.

  • The _once variants add deduplication:

    • include_once / require_once track already-included paths and skip a second load.

    • This prevents redeclaration errors (functions, classes) and re-running top-level code.

  • Rule of thumb:

    • Use require (or require_once) for files the app cannot run without (bootstrap, class definitions).

    • Use include only when the file is optional and a missing one shouldn't kill execution.

  • In practice, modern code uses an autoloader (Composer/PSR-4), so manual require_once is mostly limited to the bootstrap file.

Q32.
What kind of data structure would you use to hold multiple objects in PHP, and why?

Junior

It depends on access pattern: a plain array works for simple ordered collections, but for typed, reusable, or specialized collections the SPL data structures or a custom collection class give better intent, safety, and sometimes performance.

  • Plain array: Fine for small, simple lists or maps of objects; flexible but untyped and easy to misuse.

  • SPL structures for specific semantics:

    • SplObjectStorage: store/attach unique objects, optionally with associated data; great as an object set.

    • SplStack, SplQueue, SplDoublyLinkedList: clear LIFO/FIFO intent.

    • SplPriorityQueue, SplFixedArray: priority ordering and fixed-size integer-indexed storage.

  • Typed collection class: Wrap an array inside a class implementing IteratorAggregate and Countable to enforce element type and expose domain methods.

  • Rule of thumb: pick the structure whose semantics match your access pattern, and prefer a typed collection when type safety matters.

Q33.
What is Constructor Property Promotion in PHP 8, and how does it change class definitions?

Mid

Constructor Property Promotion lets you declare and assign class properties directly in the constructor signature, eliminating the repetitive boilerplate of declaring a property, accepting it as a parameter, and assigning it.

  • Combines three steps into one: Add a visibility modifier (public, protected, private, or readonly) to a constructor parameter and PHP declares the property, accepts the argument, and assigns it.

  • Reduces boilerplate: Data/value objects with many fields no longer need duplicated property declarations and $this->x = $x; lines.

  • Limits and notes:

    • Only works in the constructor, not other methods.

    • You can still add a custom constructor body for validation alongside promoted params.

    • Cannot promote callable typed params and cannot duplicate a property declared elsewhere.

php

// Before class Point { private float $x; private float $y; public function __construct(float $x, float $y) { $this->x = $x; $this->y = $y; } } // After (PHP 8) class Point { public function __construct( private float $x, private float $y, ) {} }

Q34.
How do Attributes (introduced in PHP 8) differ from the traditional use of Annotations/DocBlocks?

Mid

Attributes are native, structured metadata declared with #[...] syntax that the engine parses into real PHP objects, whereas DocBlock annotations are just comments parsed by third-party libraries at runtime via reflection and string parsing.

  • Annotations are comments: They live inside /** */ blocks and are invisible to PHP; libraries like Doctrine parse the raw string, so typos fail silently.

  • Attributes are first-class language constructs: They are validated by the parser, IDE-aware, and map to actual classes you instantiate via reflection with ReflectionAttribute::newInstance().

  • Type safety and discoverability: Attribute arguments are checked against the attribute class constructor; you get errors for wrong names or types rather than ignored text.

  • No string parsing overhead: Reading attributes uses reflection directly, avoiding fragile regex/comment parsing.

php

#[Attribute] class Route { public function __construct(public string $path) {} } class UserController { #[Route('/users')] public function index() {} }

Q35.
What is the 'Match' expression in PHP 8, and how does it differ from a 'Switch' statement?

Mid

The match expression returns a value based on strict comparison of a subject against conditions, making it a safer, more concise alternative to switch for value selection.

  • It is an expression, not a statement: match returns a value you can assign directly; switch only executes blocks.

  • Strict comparison: match uses === (no type juggling); switch uses loose ==.

  • No fallthrough: Each arm is isolated, so no break is needed and accidental fallthrough bugs vanish.

  • Exhaustiveness: An unmatched value throws UnhandledMatchError instead of silently doing nothing; multiple conditions can share one arm with commas.

php

$result = match($status) { 200, 201 => 'Success', 404 => 'Not Found', default => 'Unknown', };

Q36.
What are Attributes in PHP 8, and how do they improve upon the traditional way of using DocBlock annotations?

Mid

Attributes are native metadata written with #[...] that the engine compiles into real, instantiable objects accessible via reflection, replacing the fragile practice of encoding metadata in /** */ comments that PHP itself ignores.

  • Machine-readable and validated: The parser checks attribute syntax and constructor arguments, so mistakes surface as errors instead of being silently ignored like comment typos.

  • Mapped to classes: An attribute is a class marked with #[Attribute]; you read it via ReflectionClass::getAttributes() and newInstance().

  • Tooling support: IDEs and static analyzers understand attributes, giving autocompletion and refactoring that comments never had.

  • Performance: No runtime regex/string parsing of comments; reflection reads structured data directly. Common uses include routing, validation, and ORM mapping.

Q37.
When would you use an Enum instead of class constants or a separate database table?

Mid

Use an enum when you have a fixed, known set of related values that belong together and benefit from type safety and behavior; use class constants for loose scalar grouping and a database table when the set is dynamic or user-managed.

  • Choose an Enum:

    • The set is finite and fixed at code time (e.g. order statuses, suits, directions).

    • You want type safety: a parameter typed as the enum can only receive valid cases, unlike a loose string or int.

    • You want to attach methods or implement interfaces, keeping behavior with the values.

  • Choose class constants: You only need named scalar values without type guarantees or instance behavior, or for backward compatibility with older PHP.

  • Choose a database table: The values change at runtime, are managed by users/admins, or need relational integrity via foreign keys.

  • Note on backed enums: A backed enum (enum Status: string) stores a scalar per case, bridging type-safe code and a persisted column.

Q38.
How do Union Types and the mixed type improve type safety in modern PHP codebases?

Mid

Union types let you declare that a value may be one of several explicit types, while mixed means 'any type'; together they let you express intent precisely so the engine and static analyzers can catch mismatches.

  • Union types are explicit:

    • Written as int|string, they enumerate the exact allowed types, so passing anything else is a TypeError.

    • They document a function's real contract instead of forcing a vague type or no type at all.

  • mixed is the explicit 'anything':

    • It is the widest type (equivalent to int|float|string|bool|array|object|null|callable), used when you genuinely accept everything.

    • Declaring mixed signals intent clearly, unlike an absent type which is ambiguous.

  • Net effect on safety: Narrow unions over mixed wherever possible: the narrower the type, the more errors caught early and the better IDE/static analysis support.

php

function format(int|float $n): string { return number_format($n, 2); } // format('abc'); // TypeError, caught immediately

Q39.
What is the #[Override] attribute in PHP 8.3, and why is it considered a safety feature for refactoring?

Mid

#[Override] is an attribute (PHP 8.3) you place on a method to declare your intent that it overrides a parent method; if no matching parent method exists, the engine raises a compile-time error.

  • What it enforces: The method must override a method from a parent class or implemented interface, otherwise you get a fatal error.

  • Why it's a refactoring safety net:

    • If a parent renames or removes the method, your child silently stops overriding and becomes a new, dead method. #[Override] turns that silent bug into an immediate error.

    • It also catches typos in the method name that would otherwise create an accidental new method.

  • It's checked at compile time: No runtime cost; it's a declaration of intent the compiler verifies, similar to @Override in Java.

php

class Base { public function handle(): void {} } class Child extends Base { #[\Override] public function handle(): void {} // OK #[\Override] public function hndle(): void {} // Fatal: nothing to override }

Q40.
What is the difference between a Readonly Property (PHP 8.1) and a Readonly Class (PHP 8.2)?

Mid

A readonly property (PHP 8.1) makes a single property immutable after its first assignment, while a readonly class (PHP 8.2) applies that to every property automatically, making the whole object immutable.

  • Readonly property:

    • Declared per property: public readonly int $id;.

    • Can be written exactly once, from inside the declaring class scope (typically the constructor); any later write throws an Error.

    • Must be typed and cannot have a default value.

  • Readonly class:

    • Declared once: readonly class Point {} marks all instance properties as readonly implicitly.

    • Forbids untyped and static properties, and prevents adding dynamic properties.

    • Children must also be declared readonly.

  • Relationship: The class form is essentially a shorthand that saves repeating readonly on every property; great for value objects and DTOs.

php

readonly class Money { public function __construct( public int $amount, public string $currency, ) {} } $m = new Money(100, 'USD'); $m->amount = 200; // Error: cannot modify readonly property

Q41.
Explain the concept of Dependency Injection and how a Service Container facilitates it.

Mid

Dependency Injection (DI) is the principle of giving an object its dependencies from the outside instead of having it create them; a service container automates this by knowing how to build and wire those dependencies for you.

  • The core idea:

    • A class declares what it needs (usually as constructor parameters) and receives ready-made objects, rather than calling new internally.

    • This inverts control: the caller (or container) decides which concrete implementation to supply.

  • What the container adds:

    • Registration/bindings: map an interface or key to a concrete class or factory.

    • Autowiring: it reads type-hints via reflection and recursively resolves the whole dependency graph.

    • Lifetime management: it can return a shared singleton or a fresh instance each time.

  • Why it matters: Loose coupling against interfaces, easy swapping of implementations, and a single place to configure how objects are built.

php

class Mailer { public function __construct(private Transport $transport) {} } // container resolves Transport automatically when building Mailer $container->bind(Transport::class, SmtpTransport::class); $mailer = $container->get(Mailer::class);

Q42.
What is a Service Container, and how does Dependency Injection help in making PHP applications more testable?

Mid

A service container is a central registry that creates and resolves objects (services) and their dependencies; combined with DI it makes code testable because you can inject fakes or mocks instead of hard-wired real implementations.

  • What a service container does:

    • Stores bindings of abstractions to concrete implementations and builds them on demand.

    • Autowires constructor dependencies and manages whether instances are shared.

  • How DI improves testability:

    • Because dependencies arrive through the constructor, a test can pass a mock or stub directly without touching the container.

    • You can isolate the unit under test from databases, HTTP, or the clock by substituting test doubles.

    • Type-hinting interfaces (not concretes) means tests can supply any conforming implementation.

  • Contrast: Calling new RealDb() inside a class hard-codes it, so you cannot replace it in a test; DI removes that coupling.

php

class OrderService { public function __construct(private PaymentGateway $gateway) {} } // in a test, inject a fake instead of the real gateway $service = new OrderService(new FakePaymentGateway());

Q43.
What is the role of Middleware in a modern PHP framework, and how does it sit between the request and the response?

Mid

Middleware is a layer of code that wraps request handling: each middleware receives the incoming request, can act on it, optionally passes it to the next layer, and can then act on the outgoing response. It forms an onion of pipeline stages around the application core.

  • Position in the flow:

    • It sits between the HTTP request entering and the response leaving, so it sees the request on the way in and the response on the way out.

    • Standardized in PHP by PSR-15 (MiddlewareInterface with process(Request, Handler)).

  • Typical responsibilities:

    • Cross-cutting concerns: authentication, CORS, logging, sessions, rate limiting, input transformation.

    • Short-circuiting: a middleware can return a response early (e.g. a 401) and never call the next layer.

  • How chaining works: Each middleware decides whether to call $handler->handle($request) to continue, then may modify the returned response before passing it back up.

php

class AuthMiddleware implements MiddlewareInterface { public function process(Request $request, RequestHandlerInterface $handler): Response { if (! $request->hasHeader('Authorization')) { return new Response(401); // short-circuit } $response = $handler->handle($request); // pass to next layer return $response->withHeader('X-Checked', '1'); } }

Q44.
Explain the concept of an ORM, and what are the tradeoffs of using an ORM versus writing raw SQL?

Mid

An ORM (Object-Relational Mapper) maps database tables to classes and rows to objects, so you manipulate records as PHP objects instead of writing SQL by hand. It trades raw control and peak performance for productivity, safety, and portability.

  • What it does:

    • Translates objects to SQL: $user->save() becomes an INSERT/UPDATE; querying returns hydrated objects.

    • Handles relationships, migrations, and parameter binding (which guards against SQL injection).

  • Advantages:

    • Faster development and readable, expressive code.

    • Database portability: switch MySQL/PostgreSQL with little query change.

    • Built-in protection via prepared statements and consistent model logic.

  • Tradeoffs:

    • Performance overhead and the N+1 query problem (lazy loading in loops).

    • Leaky abstraction: complex reports, window functions, or heavy joins are awkward and may need raw SQL anyway.

    • Hides what the database actually does, which can mask inefficiency.

  • Pragmatic rule: use the ORM for everyday CRUD and relationships; drop to raw SQL or query builder for performance-critical or analytical queries.

Q45.
Explain Dependency Injection in Laravel. Why is it better than hard-coding class dependencies?

Mid

Dependency Injection (DI) means a class receives its dependencies from outside (typically via the constructor) instead of creating them itself. In Laravel the Service Container resolves and injects these automatically, producing loosely coupled, testable code.

  • How Laravel does it:

    • Type-hint a dependency in a constructor or controller method and the container builds it for you (autowiring).

    • Bind an interface to a concrete class in a service provider, then type-hint the interface.

  • Why it beats hard-coding:

    • Decoupling: the class depends on an abstraction, not a specific implementation, so you can swap implementations without editing it.

    • Testability: inject a mock or fake in tests instead of hitting real services.

    • Centralized configuration: object creation and lifetimes live in one place.

  • Hard-coding (new PaymentGateway() inside a class) glues the two together permanently and makes isolated testing nearly impossible.

php

class OrderController { public function __construct( private PaymentGateway $gateway // injected by the container ) {} }

Q46.
Explain the SOLID principles and give a verbal example of how Single Responsibility or Dependency Inversion applies to a PHP class.

Mid

SOLID is five object-oriented design principles that keep code maintainable, flexible, and easy to extend. They guide how classes are structured and how they depend on one another.

  • The five principles:

    • S - Single Responsibility: a class should have one reason to change.

    • O - Open/Closed: open for extension, closed for modification.

    • L - Liskov Substitution: subclasses must be usable wherever the parent is.

    • I - Interface Segregation: prefer small, focused interfaces over fat ones.

    • D - Dependency Inversion: depend on abstractions, not concretions.

  • Single Responsibility example: A UserRegistration class that validates, saves the user, AND sends a welcome email has three reasons to change. Split off a Mailer so email changes don't touch registration logic.

  • Dependency Inversion example: Instead of OrderService creating a concrete StripeGateway, it depends on a PaymentGateway interface injected via the constructor, so you can swap Stripe for PayPal without changing the service.

Q47.
When would you use a Factory pattern versus a Singleton pattern in a PHP backend?

Mid

Use a Factory when you need to create many instances and want to encapsulate or vary the construction logic; use a Singleton when exactly one shared instance should exist for the whole application lifecycle. They solve opposite problems: many objects versus one.

  • Factory pattern:

    • Centralizes object creation and decides which concrete class to build at runtime.

    • Good for: building a notification channel based on a config value, or producing different report objects from one method.

    • Returns a new (or chosen) object each call.

  • Singleton pattern:

    • Guarantees one instance with a global access point.

    • Good for: a shared resource that's expensive or must be coordinated (a config registry, a DB connection pool, a logger).

    • Caveat: it acts as global state, which hurts testability; in Laravel prefer binding a singleton in the container ($app->singleton()) over a static implementation.

  • Quick decision:

    • "I need a fresh object, possibly of varying type" -> Factory.

    • "Everyone must share the same object" -> Singleton.

Q48.
In frameworks like Laravel or Symfony, what is the difference between the 'Service Container' and a 'Service Provider'?

Mid

The Service Container is the object that stores and resolves dependencies (the registry of how to build things); a Service Provider is the place where you register those bindings into the container. One is the container itself, the other is the configuration step that fills it.

  • Service Container:

    • A central IoC container that resolves classes and injects their dependencies (autowiring).

    • You ask it for an object (app(PaymentGateway::class)) and it constructs the whole dependency graph.

  • Service Provider:

    • A class with register() (bind things into the container) and boot() (run after all bindings exist).

    • The bootstrapping entry point where packages and your app configure their services.

  • Relationship: Providers write the recipes; the container cooks the meal when something is requested.

php

// Inside a Service Provider public function register() { $this->app->bind(PaymentGateway::class, StripeGateway::class); }

Q49.
What is 'Middleware' in a PHP web application, and where does it sit in the Request/Response cycle?

Mid

Middleware is a layer of code that sits between the incoming HTTP request and your application's route handler, filtering or modifying requests and responses as they pass through. It wraps the request/response cycle like layers of an onion.

  • Where it sits:

    • After the request enters the app but before it reaches the controller; it can also act on the way back out before the response is sent.

    • Each middleware decides to pass control onward ($next($request)) or short-circuit with its own response.

  • Common uses:

    • Authentication and authorization, CSRF protection, rate limiting, CORS headers, logging.

    • Cross-cutting concerns that shouldn't clutter controllers.

  • How the chain works: Middleware runs in a pipeline; pre-handler code runs inbound, then the controller, then post-handler code runs outbound as the response bubbles back.

php

public function handle($request, Closure $next) { if (! $request->user()) { return redirect('login'); // short-circuit } $response = $next($request); // pass to next layer return $response; // can modify on the way out }

Q50.
Explain the 'Repository Pattern' in the context of a PHP framework like Laravel or Symfony. What problem does it solve?

Mid

The Repository Pattern places a layer between your business logic and data persistence: instead of querying the database directly, code asks a repository (e.g. UserRepository) for domain objects, hiding how and where they are stored.

  • The problem it solves:

    • Decouples business logic from the persistence mechanism (Eloquent, Doctrine, an API, in-memory).

    • Centralizes query logic so it is not duplicated across controllers and services.

  • Typical shape:

    • An interface (UserRepositoryInterface) defines methods like findActive(); a concrete class implements it.

    • Bind interface to implementation in the container, so consumers depend on the abstraction.

  • Benefits:

    • Testability: swap a real repository for a fake/in-memory one in unit tests.

    • Swappable storage and a single place to optimize or change queries.

  • Caveat: In Laravel, Eloquent is already an active-record abstraction; adding repositories can be over-engineering for simple CRUD. Use it when domain complexity or multiple data sources justify it.

Q51.
What is Dependency Injection, and how does a Service Container automate this process?

Mid

Dependency Injection means a class receives its dependencies from outside (usually via the constructor) rather than creating them itself; a Service Container automates this by inspecting what a class needs and building the whole object graph for you.

  • Dependency Injection:

    • Inverts control: the caller supplies collaborators, so classes are loosely coupled and easy to test (pass a mock).

    • Common forms: constructor injection (preferred), setter injection, method injection.

  • How a Service Container automates it:

    • Autowiring: it uses Reflection to read constructor type-hints and recursively resolves each dependency.

    • Bindings: you register how to build a type, e.g. map an interface to a concrete class or define a factory closure.

    • Lifetimes: it can return a new instance each time or a shared singleton.

  • Result: you ask the container for a top-level service and it assembles every nested dependency automatically.

php

// Laravel: type-hints are autowired by the container class OrderController { public function __construct( private OrderRepository $orders, private Mailer $mailer ) {} } // Bind an interface to an implementation $app->bind(PaymentGateway::class, StripeGateway::class); $app->singleton(Mailer::class, fn () => new SmtpMailer(config('mail')));

Q52.
Explain the role of 'Middleware' in the request lifecycle.

Mid

Middleware are layers that wrap the request/response cycle: each one can inspect or modify the incoming request before it reaches the controller, and the outgoing response after, forming a pipeline (the 'onion' model).

  • Pipeline position:

    • A request passes through each middleware in order, hits the route handler, then unwinds back out through the same middleware.

    • Each middleware decides whether to pass control onward (call $next($request)) or short-circuit (e.g. redirect, return 401).

  • Common responsibilities:

    • Cross-cutting concerns: authentication, authorization, CSRF, rate limiting, CORS, logging, session start.

    • Before logic (run before $next) vs after logic (run on the returned response).

  • Why it matters: Keeps controllers focused on business logic; concerns are reusable and composable per route or globally.

php

public function handle($request, Closure $next) { if (! $request->user()) { return redirect('login'); // short-circuit } $response = $next($request); // pass down the pipeline $response->header('X-Checked', '1'); // after logic return $response; }

Q53.
What is a 'Service Provider' in Laravel, and why is it called the 'central place' of application bootstrapping?

Mid

A Service Provider is a class where you register bindings into the container and bootstrap framework/package features; it is called the central place of bootstrapping because nearly everything Laravel and its packages set up happens through providers during application boot.

  • Two key methods:

    • register(): only bind things into the container (no resolving other services, which may not exist yet).

    • boot(): runs after all providers are registered, so here you wire up events, routes, view composers, validation rules, etc.

  • Why 'central place':

    • Every core service (DB, cache, queue, auth) and every installed package registers itself via a provider.

    • Providers are listed in config (config/app.php / package discovery), giving one predictable bootstrap path.

  • Performance note: Deferred providers register lazily, loading only when their binding is actually needed.

Q54.
What are 'Magic Methods' in PHP, and can you name a few common ones?

Mid

Magic methods are specially named methods (prefixed with __) that PHP calls automatically in response to certain events on an object, such as accessing an undefined property, calling an inaccessible method, or printing the object.

  • Object lifecycle: __construct() and __destruct(): run on creation and destruction.

  • Property overloading: __get(), __set(), __isset(), __unset(): triggered on inaccessible/undefined properties.

  • Method overloading: __call() for inaccessible instance methods, __callStatic() for static ones (this powers Laravel Facades).

  • Representation/invocation: __toString() (object used as string), __invoke() (object called like a function).

  • Caveat: they add flexibility but can hurt readability, IDE autocompletion, and performance, so use deliberately.

Q55.
What is a Trait, and what problem does it solve in PHP?

Mid

A Trait is a reusable bundle of methods (and properties) that can be 'mixed into' multiple classes, solving PHP's lack of multiple inheritance by letting unrelated classes share behavior without a common base class.

  • The problem it solves:

    • PHP allows only single class inheritance; traits enable horizontal code reuse across class hierarchies.

    • Avoids duplicating the same method in many classes or forcing an artificial shared parent.

  • How it behaves:

    • A class includes a trait with use; the methods are effectively copied in at compile time.

    • Conflicts between multiple traits are resolved with insteadof and as (aliasing).

  • Caveats:

    • Traits are not types: you cannot type-hint against a trait (use an interface for that).

    • Overuse can hide where behavior comes from; prefer composition when state is involved.

php

trait Loggable { public function log(string $msg): void { echo static::class . ": $msg"; } } class Order { use Loggable; } class Invoice { use Loggable; } (new Order)->log('created'); // Order: created

Q56.
What is the difference between a 'shallow copy' and a 'deep copy' when cloning objects in PHP?

Mid

A shallow copy (what clone does by default) duplicates the object but keeps references to the same nested objects, while a deep copy duplicates the nested objects too, producing a fully independent graph.

  • Shallow copy:

    • The clone keyword copies scalar properties by value, but object properties are copied by reference (both copies point to the same inner object).

    • Mutating a nested object on one copy is visible on the other.

  • Deep copy:

    • Recursively clones nested objects so nothing is shared.

    • Implement it in the __clone() magic method, which PHP calls automatically on the new copy.

  • Quick alternative: unserialize(serialize($obj)) gives a deep copy generically, but is slower and fails on resources/closures.

php

class Order { public Customer $customer; public function __clone() { // deep copy: clone the nested object too $this->customer = clone $this->customer; } } $copy = clone $order; // shallow without __clone, deep with it

Q57.
What are Traits? How do they differ from Interfaces and Abstract Classes, and what problem do they solve regarding single inheritance?

Mid

Traits are reusable units of method (and property) implementation that are "copied" into a class at compile time, letting you share code across unrelated classes without inheritance. They solve PHP's single-inheritance limit: a class can extend only one parent but can use many traits.

  • Trait:

    • Provides actual implementation (concrete methods), horizontally reused across classes.

    • Has no type identity: you can't type-hint against a trait.

  • Interface:

    • Pure contract: declares method signatures, no implementation (apart from constants/default since 8.x specifics).

    • Defines a type, so it supports polymorphism via instanceof and type hints.

  • Abstract class: Mixes contract and implementation but participates in single inheritance (one parent only).

  • Problem solved: Code reuse across class hierarchies without forcing an "is-a" relationship, avoiding deep or artificial inheritance trees.

  • Common pairing: Implement an interface (the type) with a trait (the shared implementation).

php

trait Loggable { public function log(string $msg): void { /* ... */ } } class Service { use Loggable; } class Job extends Task { use Loggable; } // reuse despite different parents

Q58.
Explain the difference between a final class and an abstract class, and when would you want to prevent a class from being inherited?

Mid

An abstract class is an incomplete base meant to be extended (it can't be instantiated directly), while a final class is a complete one that must not be extended. They sit at opposite ends: abstract demands subclassing, final forbids it.

  • Abstract class:

    • Can declare abstract methods (no body) that subclasses must implement.

    • Cannot be instantiated; only its concrete children can.

  • Final class:

    • Fully usable and instantiable, but extends on it is a fatal error.

    • You can also mark individual methods final to block overriding while still allowing subclassing.

  • When to prevent inheritance:

    • Value objects and immutable types where subclassing could break invariants.

    • Classes with security-sensitive or correctness-critical logic you don't want overridden.

    • To signal "use composition, not extension" and keep internals free to change.

Q59.
How does PHP handle object destruction, and what is the role of the __destruct() magic method?

Mid

PHP destroys an object when its last reference disappears, using reference counting plus a cycle-collecting garbage collector; at destruction it calls the object's __destruct() method so you can release resources.

  • Reference counting:

    • Each variable adds to an object's refcount; when it hits zero the object is freed and __destruct() runs.

    • unset() or going out of scope drops references.

  • Cycle collector: Reference cycles (objects referencing each other) never reach zero, so a separate GC reclaims them periodically.

  • Role of __destruct():

    • Cleanup hook: close file handles, DB connections, flush buffers.

    • Takes no arguments and can't be called with a meaningful return.

  • Caveats:

    • At script shutdown all remaining objects are destroyed in an undefined order, so don't rely on other objects still existing.

    • Exceptions thrown from __destruct() during shutdown cause fatal errors; avoid heavy or risky logic there.

Q60.
Explain how prepared statements prevent SQL injection, and why is manual string escaping insufficient?

Mid

Prepared statements separate the SQL structure from the data: the query with placeholders is sent and parsed first, then the values are sent separately as parameters, so user input is always treated as data and never as executable SQL.

  • How they prevent injection:

    • The database compiles the query plan from the template before any value is bound, so input can't change the command's meaning.

    • Placeholders (? or :name) carry values out-of-band, not by string concatenation.

  • Why manual escaping is insufficient:

    • Easy to forget one variable, and one miss is a vulnerability.

    • Charset/encoding mismatches can defeat escaping functions.

    • Escaping doesn't help for unquoted contexts like numeric values, identifiers, or LIMIT clauses.

  • Caveat: Parameters bind values, not table/column names; validate identifiers against an allowlist.

php

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email'); $stmt->execute(['email' => $userInput]); // input can never alter the query

Q61.
Explain the concept of Traits. Why would you use them instead of traditional inheritance?

Mid

Traits let you share concrete method implementations horizontally across classes that don't belong to the same hierarchy, working around PHP's single-inheritance restriction. You use them when behavior is reusable but an "is-a" parent relationship would be wrong or impossible.

  • Why over inheritance:

    • A class extends only one parent, but can use many traits, composing behavior from several sources.

    • Avoids forcing artificial parent classes just to reuse a method.

    • Keeps cross-cutting behavior (logging, serialization, comparison) in one place.

  • Mechanics:

    • Methods are copied into the class at compile time, as if written there.

    • Traits can hold properties and abstract/static methods.

  • Trade-offs:

    • No type identity (can't type-hint a trait), so pair with an interface when you need polymorphism.

    • Overuse hides where behavior lives and can cause naming collisions; prefer composition for complex state.

Q62.
Explain 'Trait' conflict resolution. What happens if two traits used in the same class have the same method name?

Mid

If two traits used in the same class define a method with the same name, PHP raises a fatal error unless you explicitly resolve the conflict with the insteadof and as operators in the use block.

  • insteadof: Chooses which trait's method to keep, excluding the other.

  • as:

    • Aliases the excluded method to a new name so both remain accessible.

    • Can also change method visibility (e.g. expose as protected).

  • Precedence rules: A method defined directly in the class overrides a trait method; a trait method overrides one inherited from a parent.

php

trait A { public function hello() { return 'A'; } } trait B { public function hello() { return 'B'; } } class C { use A, B { A::hello insteadof B; // use A's version B::hello as helloFromB; // keep B's under a new name } }

Q63.
What are 'Magic Methods' in PHP? Explain the specific use cases for __call and __invoke.

Mid

Magic methods are predefined methods (prefixed with __) that PHP invokes automatically in response to certain events on an object, letting you hook into operations like inaccessible method calls, property access, or treating an object as a function.

  • They are event hooks, not normal methods: PHP calls them implicitly: you rarely call __construct(), __toString(), __get() directly.

  • __call(\$name, \$args):

    • Invoked when calling an inaccessible or non-existent instance method.

    • Use cases: proxies/decorators, fluent dynamic APIs (e.g. whereName() routed to a query builder), or delegating to a wrapped object.

    • Static version is __callStatic().

  • __invoke(...\$args):

    • Invoked when an object is used as if it were a function: \$obj().

    • Use cases: single-responsibility "action" or invokable classes, middleware, callables passed to array_map() or route handlers.

php

class Repository { public function __call($name, $args) { // route undefined calls to a query builder return $this->query->$name(...$args); } } class SendEmail { public function __invoke(string $to): bool { return $this->mailer->send($to); } } $send = new SendEmail(); $send('a@b.com'); // triggers __invoke

Q64.
How does 'Constructor Property Promotion' simplify class definitions, and what are its limitations regarding inheritance?

Mid

Constructor Property Promotion (PHP 8.0+) lets you declare and assign constructor parameters as class properties in one place by adding a visibility modifier to the parameter, removing the boilerplate of declaring a property and manually assigning it.

  • What it eliminates:

    • No separate property declaration, no $this->x = $x; assignment line per field.

    • Trigger it with a visibility keyword (public, protected, private) on the parameter.

  • Constraints:

    • Only works in __construct(), not other methods.

    • Cannot be used in abstract constructors or interfaces; not allowed for callable types.

  • Inheritance limitation:

    • A subclass that defines its own constructor does not automatically inherit promoted properties: you must call parent::__construct() and re-pass the values.

    • You cannot "partially" promote in a child while reusing the parent's promotion: the child constructor must explicitly forward arguments.

php

class Point { public function __construct( public int $x = 0, public int $y = 0, ) {} } class Point3D extends Point { public function __construct(int $x, int $y, public int $z = 0) { parent::__construct($x, $y); // must forward explicitly } }

Q65.
What are 'Magic Methods' in PHP (e.g., __call, __get, __set), and what are the trade-offs of using them?

Mid

Magic methods are special hooks PHP calls automatically for events like accessing missing properties or calling missing methods. They enable powerful dynamic behavior, but trade away clarity, performance, and IDE/static-analysis support, so use them deliberately.

  • Common ones:

    • __get(\$name) / __set(\$name, \$value): triggered when reading/writing inaccessible or undefined properties.

    • __call() / __callStatic(): triggered for inaccessible method calls.

    • __isset(), __unset(), __toString(), __invoke() round out the set.

  • Benefits: Concise dynamic APIs: ORMs (Eloquent attributes), proxies, lazy loading, fluent interfaces.

  • Trade-offs:

    • Performance: magic accessors are slower than direct property access.

    • Tooling: IDE autocompletion and static analyzers can't see dynamic members, so refactoring and type safety suffer.

    • Readability/debugging: behavior is implicit and hidden, making bugs harder to trace.

    • Often a better fit: explicit methods or PHP 8 #[\AllowDynamicProperties] only when truly needed.

Q66.
What is the purpose of the php.ini file, and which settings are most critical for production security?

Mid

php.ini is the main runtime configuration file that controls how the PHP interpreter behaves: error reporting, resource limits, extension loading, security features, and upload/session settings. In production, the goal is to disable information leakage and dangerous features while keeping safe limits.

  • What it controls: Per-environment behavior loaded at startup (one for CLI, one for the web SAPI like FPM).

  • Critical production security settings:

    • display_errors = Off: never show stack traces/paths to users; log instead via log_errors = On.

    • expose_php = Off: hide the PHP version from the X-Powered-By header.

    • disable_functions: disable dangerous calls like exec, shell_exec, system if unused.

    • allow_url_fopen / allow_url_include = Off: prevent remote file inclusion.

    • session.cookie_httponly = On, session.cookie_secure = On, session.use_strict_mode = On: harden session cookies.

    • open_basedir: restrict filesystem access; set sane upload_max_filesize and memory_limit.

Q67.
What are the most common security vulnerabilities in PHP applications (e.g., SQL Injection, XSS), and how do you conceptually prevent them?

Mid

The most common PHP vulnerabilities come from trusting untrusted input: SQL Injection, XSS, CSRF, file inclusion, and insecure deserialization. The unifying defense is to separate code from data: never let user input become executable SQL, HTML, or commands.

  • SQL Injection: Input alters query structure. Prevent with prepared statements / parameter binding (PDO or mysqli), never string concatenation.

  • Cross-Site Scripting (XSS): Injected scripts run in the victim's browser. Prevent by output-escaping (htmlspecialchars()) in the right context plus a Content-Security-Policy.

  • Cross-Site Request Forgery (CSRF): Forged authenticated requests. Prevent with per-form CSRF tokens and SameSite cookies.

  • File inclusion / path traversal: User input in include or file paths. Whitelist allowed values; disable allow_url_include.

  • Insecure deserialization: unserialize() on user data can trigger object injection. Use json_decode() or restrict allowed classes.

  • Cross-cutting principle: Validate input, escape output, use least privilege, and keep secrets/errors out of responses.

Q68.
Why is password_hash() preferred over md5() or sha1(), even if those are salted?

Mid

Because password_hash() uses slow, adaptive algorithms designed specifically for passwords, while md5() and sha1() are fast general-purpose hashes that even with salt fall to brute-force attacks.

  • MD5/SHA1 are too fast: Modern GPUs compute billions per second, so an attacker can guess salted hashes incredibly quickly even though salting stops precomputed rainbow tables.

  • Salt alone is not enough: Salting only prevents reuse of precomputed tables; it does nothing to slow down per-guess cracking speed.

  • password_hash() is adaptive and slow:

    • Defaults to bcrypt (or Argon2), with a tunable cost factor you can raise as hardware improves.

    • It generates a cryptographically secure random salt automatically and embeds it in the output string.

  • Built-in verification and upgrade path: Pair it with password_verify() and password_needs_rehash() to migrate hashes to stronger parameters over time.

php

$hash = password_hash($password, PASSWORD_DEFAULT); if (password_verify($input, $hash)) { // optionally re-hash if cost has increased if (password_needs_rehash($hash, PASSWORD_DEFAULT)) { $hash = password_hash($input, PASSWORD_DEFAULT); } }

Q69.
Explain the difference between CSRF (Cross-Site Request Forgery) and XSS (Cross-Site Scripting) in a PHP application.

Mid

Both are web attacks but target different trust relationships: XSS injects malicious script that runs in a victim's browser, while CSRF tricks an authenticated user's browser into sending an unwanted request to your site using their existing credentials.

  • XSS: abuses the user's trust in your site:

    • Attacker's script executes in the victim's browser to steal cookies, hijack sessions, or rewrite the page.

    • Defense: escape all output with htmlspecialchars(), set a Content-Security-Policy, and use HttpOnly cookies.

  • CSRF: abuses your site's trust in the user's browser:

    • A forged request (e.g. a hidden form or image) rides on the victim's logged-in session cookie to perform actions they didn't intend.

    • Defense: per-request CSRF tokens validated server-side, plus SameSite cookies and checking the request method.

  • Key distinction: XSS runs code inside the page; CSRF sends a request without needing to run code on your page, just relying on the browser auto-sending credentials.

Q70.
How would you handle file uploads securely in PHP?

Mid

Secure file uploads require validating the file on the server, storing it outside the web root, and never trusting client-supplied data like the file name or MIME type. The goal is to prevent attackers from uploading and then executing malicious scripts.

  • Validate server-side:

    • Check $_FILES['x']['error'] and enforce a size limit.

    • Detect the real type with finfo_file() instead of trusting the browser-sent MIME or extension.

    • Use is_uploaded_file() and move_uploaded_file() to handle the temp file safely.

  • Neutralize the file name: Generate your own random name and assign an extension from your whitelist; never use the original name directly (path traversal, double extensions).

  • Store and serve safely:

    • Save outside the web root (or in a directory where script execution is disabled) and serve via a controller that sets the right headers.

    • For images, re-process/re-encode them to strip embedded code.

  • Whitelist over blacklist: Allow only known-good types/extensions rather than trying to block dangerous ones.

Q71.
What is the difference between an Interface and an Abstract Class, and when would you choose one over the other?

Mid

An interface is a pure contract that defines what methods a class must implement with no behavior, while an abstract class is a partial implementation that can hold shared code and state but cannot be instantiated. Use an interface to define a capability across unrelated classes; use an abstract class to share a common base among related ones.

  • Interface:

    • Only method signatures (and constants); no implementation or instance state.

    • A class can implement many interfaces, enabling multiple-capability typing.

  • Abstract class:

    • Can mix concrete methods, properties, and abstract methods subclasses must define.

    • A class can extend only one (single inheritance).

  • When to choose which:

    • Interface: define a behavior contract that many, possibly unrelated, classes share (e.g. Countable, JsonSerializable).

    • Abstract class: provide reusable base logic plus enforced hooks for related types.

    • Common practice: code against an interface, optionally provide an abstract base that implements it.

php

interface PaymentGateway { public function charge(int $cents): bool; } abstract class BaseGateway implements PaymentGateway { protected function log(string $msg): void { /* shared */ } abstract public function charge(int $cents): bool; // each must define }

Q72.
What is the difference between an Interface and an Abstract Class in PHP?

Mid

An interface defines a pure contract of method signatures with no implementation, while an abstract class is a partially implemented base class that can mix concrete and abstract members. A class implements many interfaces but extends only one abstract class.

  • Interface:

    • Declares method signatures (and constants) only; before PHP 8 it could hold no implementation.

    • All methods are implicitly public; a class can implement multiple interfaces.

    • Expresses a capability or role ("can do this").

  • Abstract class:

    • Can define concrete methods, properties, constructors, and abstract methods that subclasses must implement.

    • Supports any visibility and cannot be instantiated directly.

    • Expresses an "is-a" relationship with shared base behavior.

  • Key rule: single inheritance for abstract classes, multiple implementation for interfaces.

  • Rule of thumb: use an interface for a contract many unrelated classes share; use an abstract class to share real code among related subclasses.

Q73.
What is method chaining (fluent interface), and how is it implemented in PHP?

Mid

Method chaining (a fluent interface) lets you call multiple methods on the same object in one expression, by having each method return $this so the next call continues on the same instance.

  • The mechanism:

    • Each setter/configuration method ends with return $this; instead of returning void.

    • The returned object exposes the next method, so calls flow left to right.

  • Why use it: Produces readable, expressive APIs (query builders, validators, HTTP clients).

  • Caveat: Only works for methods meant to mutate/configure; methods that return a real value (like a query result) break the chain.

php

class QueryBuilder { private array $parts = []; public function select(string $cols): static { $this->parts['select'] = $cols; return $this; } public function from(string $t): static { $this->parts['from'] = $t; return $this; } public function where(string $c): static { $this->parts['where'] = $c; return $this; } } $sql = (new QueryBuilder()) ->select('id, name') ->from('users') ->where('active = 1');

Q74.
What is the difference between abstract methods and interface methods in terms of implementation requirements?

Mid

Both abstract methods and interface methods define a contract without a body, but they differ in where they live and what else they can carry: an interface is a pure contract, while an abstract class can mix abstract and concrete code.

  • Interface methods:

    • Are always implicitly public and have no body; the implementing class must define every one.

    • A class can implement many interfaces (implements A, B), enabling multiple type contracts.

  • Abstract methods (in an abstract class):

    • Declared with abstract and no body; the first concrete subclass must implement them.

    • Live alongside concrete methods, properties, and constructors, so the parent can share real implementation.

    • Limited to single inheritance (one extends).

  • Shared rule: In both cases the child fails to compile if it leaves a declared method unimplemented (unless the child is itself abstract).

  • Rule of thumb: Use an interface for a pure capability contract; use an abstract class when you also want to share base behavior.

Q75.
How does PHP handle sessions, and where is session data typically stored?

Mid

A PHP session keeps per-user state across stateless HTTP requests by issuing a unique session ID (stored in a cookie) and saving the associated data server-side, keyed by that ID.

  • How it works:

    • session_start() reads the PHPSESSID cookie (or sets one) and loads data into the $_SESSION superglobal.

    • You read/write $_SESSION; PHP serializes and persists it at request end.

  • Where data is stored:

    • By default in files on the server (session.save_path, e.g. /tmp), one file per session.

    • Configurable via session.save_handler to use Redis, Memcached, or a database, which is required when multiple web servers share sessions.

  • On the client: Only the session ID is sent in the cookie; the actual data never leaves the server.

  • Security notes: Use session_regenerate_id() after login to prevent fixation, and set HttpOnly/Secure cookie flags.

Q76.
Can you explain the PHP request-response cycle from the moment a user hits a URL to the point the HTML is rendered?

Mid

From a user hitting a URL, the browser sends an HTTP request that the web server routes to PHP, PHP executes the script (often through a framework front controller) and emits HTML, which the server returns and the browser renders.

  1. Client request: DNS resolves the host, a TCP/TLS connection opens, and the browser sends an HTTP request to the server.

  2. Web server dispatch: Nginx/Apache serves static assets directly or forwards dynamic requests to PHP (via PHP-FPM/FastCGI).

  3. PHP execution:

    • A front controller (e.g. index.php) bootstraps, routes the request, runs controller logic, and queries the database as needed.

    • Output is built (HTML from a template/view) and sent back with headers and a status code.

  4. Response return: The web server relays the response over the same connection to the browser.

  5. Browser rendering: The browser parses HTML, fetches linked CSS/JS/images (each a further request), builds the DOM, and paints the page.

Q77.
Explain the PHP request-response lifecycle from the moment a request hits the web server to the final HTML output.

Mid

A request travels from the web server to the PHP engine, which compiles and executes your script (often through a framework) and returns generated output as the HTTP response.

  1. Web server receives the request: A server like Nginx or Apache parses the HTTP request and decides PHP must handle it (by extension or routing rules).

  2. Handoff to the PHP runtime: With PHP-FPM, the server forwards it over FastCGI to a worker process; with mod_php the interpreter is embedded in Apache.

  3. Compilation and execution:

    • PHP parses the script into opcodes (cached by OPcache to skip recompilation), then the Zend Engine executes them.

    • Superglobals like $_GET, $_POST, and $_SERVER are populated for the script.

  4. Application logic runs: In a framework, a front controller routes the request, runs middleware/controllers, queries the database, and renders a view into output.

  5. Response is built and sent: Echoed output plus headers go back through the server to the client as the HTTP response.

  6. Shutdown: PHP is shared-nothing: it tears down request state and frees memory, so each request starts fresh.

Q78.
How does PHP-FPM work, and what are the advantages of using it over the older mod_php?

Mid

PHP-FPM (FastCGI Process Manager) is a separate process pool that the web server talks to over FastCGI, decoupling PHP execution from the web server and giving you better performance, isolation, and control than embedding PHP inside Apache.

  • How it works:

    • A master process manages a pool of long-lived worker processes; the web server forwards requests via FastCGI and a free worker executes the script.

    • Process count is tuned with directives like pm = dynamic, pm.max_children, and pm.start_servers.

  • Advantages over mod_php:

    • Server-agnostic: works with Nginx (which has no PHP module), not just Apache.

    • Lower memory: the web server doesn't carry a PHP interpreter in every request thread.

    • Isolation and control: separate pools can run under different users/configs, improving security and resource tuning.

    • Resilience: workers can be recycled (pm.max_requests) to limit memory leaks without restarting the server.

  • Trade-off: mod_php was simpler to configure and slightly faster per-request in-process, but it ties PHP to Apache's prefork model and bloats memory.

Q79.
What are PSR standards, and why are they important for the PHP ecosystem?

Mid

PSR (PHP Standards Recommendations) are specifications published by the PHP-FIG group that define common conventions so independently written code and libraries can interoperate.

  • What they cover: Autoloading (PSR-4), coding style (PSR-12), interfaces like PSR-3 (logging), PSR-7 (HTTP messages), and PSR-11 (container).

  • Why they matter:

    • Interoperability: shared interfaces let you swap a PSR-3 logger or PSR-7 implementation without rewriting code.

    • Consistency: a common style lowers the cost of moving between projects and teams.

    • Ecosystem glue: Composer and modern frameworks rely on PSR autoloading and interfaces to integrate packages cleanly.

  • Status: PSRs are recommendations, not enforced rules, but adopting them is the de facto professional standard.

Q80.
What is the purpose of the composer.lock file compared to composer.json?

Mid

composer.json declares the versions you allow, while composer.lock records the exact versions actually installed, so every environment gets an identical, reproducible dependency tree.

  • composer.json: Human-edited; lists dependencies with version constraints (e.g. ^8.1) describing acceptable ranges.

  • composer.lock:

    • Auto-generated; pins the exact resolved version and commit hash of every package, including transitive ones.

    • composer install reads the lock file to reproduce that exact set; composer update re-resolves and rewrites it.

  • Practical rule: Always commit composer.lock for applications so deployments are deterministic; libraries often omit it.

Q81.
Explain how Autoloading works in modern PHP. Why is it preferred over manual require or include?

Mid

Autoloading lets PHP load class files on demand the first time a class is referenced, using a registered callback instead of manual file includes, with Composer's PSR-4 autoloader being the modern standard.

  • How it works:

    • When an undefined class is used, PHP invokes functions registered via spl_autoload_register() to locate and include the file.

    • PSR-4 maps a namespace prefix to a base directory, so App\Models\User resolves to src/Models/User.php.

    • Composer generates this from the autoload section; you just include vendor/autoload.php once.

  • Why it beats manual require/include:

    • Lazy loading: only files actually used are loaded, saving memory and time.

    • No fragile, manual include lists to maintain or reorder.

    • Optimizable: composer dump-autoload -o builds a classmap for production speed.

Q82.
What are PSR standards (e.g., PSR-4, PSR-12), and why are they important for a professional PHP project?

Mid

PSR standards are shared specifications from PHP-FIG; PSR-4 standardizes autoloading and PSR-12 standardizes coding style, together making code interoperable and consistent across teams and packages.

  • PSR-4 (autoloading): Defines how a fully-qualified class name maps to a file path, enabling Composer to autoload classes without manual includes.

  • PSR-12 (coding style):

    • Extends the earlier PSR-2 with rules for indentation, braces, imports, and spacing so all code reads uniformly.

    • Enforceable with tools like PHP_CodeSniffer or PHP-CS-Fixer.

  • Why they matter professionally:

    • Packages from different vendors integrate cleanly via shared conventions.

    • Consistent style reduces friction in code review and onboarding.

    • Standards can be automated in CI, keeping quality objective rather than personal preference.

Q83.
What are PSR standards (e.g., PSR-4, PSR-12), and why are they critical for the PHP ecosystem?

Mid

PSR standards are PHP-FIG recommendations that the whole ecosystem builds on: PSR-4 underpins autoloading and PSR-12 enforces a common code style, so independent libraries and tools can work together seamlessly.

  • Key examples:

    • PSR-4: namespace-to-path autoloading, the foundation Composer's autoloader relies on.

    • PSR-12: a detailed coding style guide for consistent formatting.

    • Interface PSRs like PSR-3 (logger), PSR-7 (HTTP), and PSR-11 (container) define swappable contracts.

  • Why they're critical:

    • Interoperability: code written against a PSR interface can use any compliant implementation.

    • Composer and frameworks (Laravel, Symfony) assume PSR autoloading, so packages just plug in.

    • Common style and contracts reduce vendor lock-in and make collaboration across the community feasible.

Q84.
Explain the difference between the == and === operators, and why is type-juggling considered a security risk in PHP?

Mid

== coerces operands to a common type before comparing while === demands identical type and value; relying on coercion (type juggling) is a security risk because attacker-controlled input can satisfy comparisons it shouldn't.

  • The operators:

    • == converts types, e.g. "abc" == 0 was true before PHP 8.

    • === never converts, so it is the safe default.

  • Why juggling is dangerous:

    • Magic hashes: two different password hashes that both look like 0e... are treated as scientific notation and compared as equal numbers (0 == 0).

    • Authentication bypass: comparing a secret token with == can let crafted input match unexpectedly.

  • Defenses:

    • Use === for comparisons and hash_equals() for secrets/tokens.

    • PHP 8 changed string-to-number rules, reducing (but not eliminating) the footguns.

Q85.
What is the difference between 'Strict Types' and the default coercive typing in PHP?

Mid

By default PHP uses coercive typing: it silently converts arguments and return values to match declared types when possible; strict_types turns that off per file, so a type mismatch throws a TypeError instead of being coerced.

  • Coercive mode (default):

    • A function typed int called with "5" or 5.0 silently converts to 5.

    • Convenient but can hide bugs and lose data (e.g. truncating floats).

  • Strict mode:

    • Enabled with declare(strict_types=1); as the first statement of a file.

    • Types must match exactly (the one exception: int is accepted where float is declared).

    • It is per-file and applies to the call site's file, not the function's definition.

  • Most teams enable strict types for safer, more predictable code.

php

declare(strict_types=1); function add(int $a, int $b): int { return $a + $b; } add("5", 2); // TypeError in strict mode; would coerce to 7 by default

Q86.
What is the null coalescing operator (??) and the nullsafe operator (?->), and when would you use each?

Mid

The null coalescing operator ?? returns its left side unless it's null or undefined, in which case it returns the right side; the nullsafe operator ?-> calls a method or accesses a property only if the object isn't null, otherwise the whole chain evaluates to null.

  • Null coalescing ??:

    • Provides a default for missing/null values without a warning: $name = $_GET['name'] ?? 'guest';.

    • The assignment form ??= sets a variable only if it's currently null/unset.

  • Nullsafe ?-> (PHP 8.0+): Short-circuits a method/property chain when an intermediate is null, avoiding "call on null" errors: $country = $user?->getAddress()?->country;.

  • When to use each:

    • Use ?? to supply a fallback value; use ?-> to safely navigate an object graph that may contain nulls.

    • They combine well: $user?->getName() ?? 'Anonymous'.

Q87.
What is the difference between Laravel and Symfony in terms of philosophy and developer experience?

Mid

Both are mature PHP frameworks, but Laravel optimizes for developer happiness and rapid delivery with opinionated conventions, while Symfony optimizes for engineering rigor, decoupled components, and explicit configuration.

  • Laravel: convention over configuration:

    • Expressive, batteries-included API (Eloquent, Blade, Artisan) that gets you productive fast.

    • Favors a smooth, fluent developer experience over strict architectural purity.

  • Symfony: explicit and component-based:

    • Reusable, decoupled components (HttpFoundation, Console, EventDispatcher) that many other tools, including Laravel, build on.

    • More configuration up front (YAML/attributes, services, DI container) but greater control and predictability.

  • Philosophy difference: Laravel hides complexity behind helpers and facades; Symfony surfaces it as explicit, swappable services.

  • Practical takeaway: Laravel for speed-to-market and smaller teams; Symfony for long-lived enterprise systems needing strict structure and reusability.

Q88.
What is the difference between a 'Job Queue' and a 'Cron Job'? When would you move a task from a controller to a background queue?

Mid

A cron job is a time-based scheduler that runs a task on a fixed clock interval, while a job queue runs tasks on demand, asynchronously, in response to events. You move work out of a controller into a queue whenever the task is slow, can fail and retry, or doesn't need to finish before responding to the user.

  • Cron job: schedule-driven:

    • Triggered by the clock (every minute, nightly, etc.), independent of user actions.

    • Good for recurring batch work: reports, cleanups, digests.

  • Job queue: event-driven:

    • A producer pushes a job; a worker process consumes it asynchronously, with retries and backoff on failure.

    • Backed by Redis, a database table, or SQS; workers run separately from web requests.

  • When to push from controller to queue:

    • Slow or external work: sending email, image processing, calling third-party APIs.

    • The user doesn't need the result immediately, so you respond fast and process in the background.

    • The task should survive failure and retry without blocking the request.

  • They combine: A cron job often just dispatches many queue jobs (e.g. nightly cron enqueues a job per user).

Q89.
Explain the 'N+1 Query Problem' in Eloquent or Doctrine and how 'Eager Loading' resolves it conceptually.

Mid

The N+1 problem is when you run 1 query to fetch a list of parent records, then trigger 1 additional query per parent to load its related data, resulting in N+1 total queries. Eager loading fixes it by fetching all the related records up front in a single extra query and matching them in memory.

  • How it happens:

    • You load 100 posts (1 query), then loop and access $post->author on each, lazily firing 100 more queries.

    • Total: 101 queries that scale with row count, hammering the database.

  • Why eager loading helps:

    • It collects all parent IDs and loads relations in one query using WHERE id IN (...).

    • Result: 2 queries total regardless of how many parents (one for posts, one for all authors).

  • How you express it:

    • Eloquent: Post::with('author')->get().

    • Doctrine: a DQL JOIN FETCH or fetch-mode EAGER.

Q90.
What is the difference between 'Eager Loading' and 'Lazy Loading' in an ORM (like Eloquent or Doctrine), and how does it affect the N+1 query problem?

Mid

Lazy loading defers loading a relation until you actually access it, while eager loading fetches the relation alongside the parent in advance. Lazy loading is what causes the N+1 problem in loops; eager loading prevents it by batching the related fetch into one query.

  • Lazy loading:

    • Relation is queried on first access ($post->comments), which is convenient but dangerous inside loops.

    • Fine when you access one record's relation occasionally and don't know you'll need it.

  • Eager loading:

    • Relations are loaded up front in one batched query, ideal when you'll iterate a collection.

    • Risk: over-fetching data you never use, so load only the relations you need.

  • Effect on N+1: Lazy loading inside a loop = N+1 queries; eager loading collapses that to a constant number.

  • Tradeoff summary: Lazy = lower memory, risk of many queries; eager = fewer queries, risk of loading too much.

Q91.
How does caching work in PHP applications, and what is the difference between using Redis and Memcached?

Mid

Caching in PHP stores the result of expensive work (DB queries, rendered views, computed data) in fast storage so subsequent requests skip the cost. Redis and Memcached are both in-memory key-value stores used for this, but Redis is a richer data-structure server with persistence, while Memcached is a leaner, purely volatile cache.

  • Layers of caching in PHP:

    • Opcode cache (OPcache) caches compiled bytecode so scripts aren't re-parsed each request.

    • Application/data cache: store query results or fragments in Redis/Memcached with a TTL.

  • Redis:

    • Rich types: strings, hashes, lists, sets, sorted sets; supports pub/sub and queues.

    • Optional persistence (snapshots/AOF) so the cache can survive restarts.

    • Effectively single-threaded for commands, but very fast and feature-rich.

  • Memcached:

    • Simple string key-value only, multi-threaded, purely in-memory (data lost on restart).

    • Slightly leaner for plain large-scale string caching.

  • How to choose: Default to Redis for its features (persistence, structures, queues); pick Memcached only for a simple, multi-threaded volatile cache.

Q92.
What are the tradeoffs between using $_GET and $_POST, and when is it appropriate to use $_REQUEST and why is it often discouraged?

Mid

Choose $_GET for visible, shareable, read-only parameters and $_POST for sensitive or state-changing data; $_REQUEST merges sources for convenience but is discouraged because it hides where the data came from.

  • $_GET tradeoffs

placeholder

Q93.
Does PHP pass objects by value or by reference by default, and how does this impact memory usage?

Mid

PHP passes objects by handle (an identifier), not a full copy: when you pass an object, both variables point to the same underlying object instance, so mutating it in one place affects the other. This is often mistaken for by reference, but it is technically pass-by-value of the handle.

  • Scalars are copied, objects are not: Passing an array or int copies the value (copy-on-write); passing an object copies only the small handle pointing to the same instance.

  • Not the same as & references:

    • Reassigning the parameter to a new object inside a function does NOT change the caller's variable; only mutating the shared object's state does.

    • True & references would also let you swap what the caller's variable points to.

  • Memory impact:

    • Cheap to pass large objects: no deep copy, just a handle, so memory stays flat.

    • Use clone when you genuinely need an independent copy (a shallow copy by default).

php

function mutate(stdClass $o) { $o->x = 1; } // affects caller function reassign(stdClass $o) { $o = new stdClass(); } // does NOT $a = new stdClass(); mutate($a); // $a->x === 1 reassign($a); // $a unchanged

Q94.
What is OPcache, and how does it improve the execution speed of PHP scripts?

Mid

OPcache is a bundled PHP extension that stores precompiled script bytecode in shared memory, eliminating the repeated work of reading and compiling PHP source on every request. This removes most of the per-request compilation overhead and significantly boosts throughput.

  • The normal request lifecycle without caching: PHP reads the file, tokenizes it, parses it into an AST, and compiles it to opcodes, then the Zend VM executes those opcodes, repeated every single request.

  • What OPcache changes:

    • It compiles once and stores the opcodes in shared memory; subsequent requests skip straight to execution.

    • Saves CPU (no re-parse/compile) and disk I/O (no re-reading source).

  • Key settings: opcache.memory_consumption, opcache.max_accelerated_files, and opcache.validate_timestamps control cache size and whether changed files are re-checked.

  • Result: Faster response times and higher requests-per-second with no code changes; it is one of the simplest high-impact PHP optimizations.

Q95.
What is OpCache, and how does it improve the performance of PHP applications?

Mid

OpCache is a bundled PHP extension that caches the compiled bytecode (opcodes) of scripts in shared memory, so PHP skips the parse-and-compile step on subsequent requests.

  • The problem it solves: By default PHP reads, tokenizes, parses, and compiles every.phpfile to opcodes on every single request, which is wasted CPU.

  • What OpCache does:

    • Stores the compiled opcodes in shared memory after the first request, so later requests execute directly from cache.

    • Reduces CPU usage and latency, often a large throughput win with no code changes.

  • Key settings:

    • opcache.memory_consumptionandopcache.max_accelerated_filessize the cache.

    • opcache.validate_timestamps: disable in production for max speed (but you must clear cache on deploy).

  • JIT (PHP 8+): OpCache also hosts the JIT compiler, which can compile hot opcodes to native machine code: helps CPU-bound code more than typical I/O-bound web apps.

Q96.
What are Anonymous Functions (Closures) and how do they use the use keyword?

Mid

An anonymous function (closure) is a function with no name, assignable to a variable or passed as an argument. Because a closure does not automatically see the enclosing scope's variables, theusekeyword explicitly imports the ones you want to capture.

  • What they are: Instances of theClosureclass, commonly used as callbacks forarray_map,usort, event handlers, etc.

  • Theusekeyword:

    • Imports outer variables into the closure's scope, captured by value by default (a snapshot at definition time).

    • Prefix with&to capture by reference so changes propagate both ways.

  • Related forms:

    • Arrow functions (fn() => ..., PHP 7.4) capture outer variables automatically by value, so they need nouse.

    • Inside an object, a closure can bind$this; adjust withClosure::bind().

php

$factor = 3; $byValue = function ($n) use ($factor) { return $n * $factor; // sees snapshot of $factor }; $total = 0; $accumulate = function ($n) use (&$total) { $total += $n; // by reference, mutates outer $total };

Q97.
Explain how PHP handles errors vs. exceptions since PHP 7/8.

Mid

Since PHP 7, most fatal errors were converted into throwable objects, so traditional "errors" and "exceptions" now share a common interface and can be caught uniformly. The hierarchy splits intoError(engine-level problems) andException(application-level problems), both implementingThrowable.

  • The unified hierarchy:

    • Throwableis the root interface; bothErrorandExceptionimplement it.

    • You cannot implementThrowabledirectly in userland: you must extend one of those classes.

  • Errors vs exceptions:

    • Errorsignals engine faults likeTypeError,DivisionByZeroError, or calling an undefined method (formerly fatal).

    • Exceptionrepresents recoverable application conditions you throw and handle deliberately.

  • Legacy warnings/notices:

    • Non-fatal diagnostics (E_WARNING,E_NOTICE) are NOT throwables; they go through the error handler, though PHP 8 promoted several previously-warnings to thrown errors.

    • Convert them withset_error_handler()throwing anErrorException.

  • Catching both: Type-hintcatch (Throwable $e)to handle errors and exceptions together.

php

try { intdiv(1, 0); // throws DivisionByZeroError (an Error) } catch (Throwable $e) { // catches both Error and Exception echo $e->getMessage(); }

Q98.
What are the performance and debugging tradeoffs of using the error control operator (@)?

Mid

The @ operator suppresses error messages from the expression it prefixes. It is convenient but costly and dangerous: it hides errors you may need to see and adds runtime overhead, so it should be avoided in favor of proper checks.

  • Performance cost: Internally PHP still triggers the error and temporarily swaps the error reporting level around the expression, so suppressed calls are slower than unsuppressed ones.

  • Debugging cost:

    • It silences warnings/notices that signal real bugs (missing files, undefined keys), so failures surface later and far from their cause.

    • It does not suppress fatal errors or (in modern PHP) most exceptions, so it gives a false sense of safety.

  • Better alternatives:

    • Check preconditions (isset(), file_exists()) or use exceptions and try/catch instead.

    • Set a strict error_reporting level and log rather than hide.

  • Legitimate uses are rare: occasionally wrapping a function that emits an unavoidable warning while you handle the return value yourself.

Q99.
What is the difference between a generator (using yield) and returning a full array, and when would you use one?

Mid

A generator uses yield to produce values lazily one at a time, while returning a full array builds and holds every value in memory at once. Use a generator for large or streamed sequences; use an array when you need the whole set in memory (counting, random access, reuse).

  • Memory:

    • Generators keep only the current value, so they handle huge or infinite sequences in near-constant memory.

    • An array allocates space for all elements up front.

  • Evaluation timing: Generators are lazy: each value is computed on demand as you iterate.

  • Limitations of generators: Forward-only and single-pass: no random access, no count() without consuming, and you cannot reuse it after iterating.

  • When to use which:

    • Generator: reading large files line by line, streaming DB rows, pipelines.

    • Array: small results, or when you need indexing, counting, sorting, or multiple passes.

php

function readLines(string $path): Generator { $fh = fopen($path, 'r'); while (($line = fgets($fh)) !== false) { yield rtrim($line); // lazy: one line in memory at a time } fclose($fh); } foreach (readLines('huge.log') as $line) { // process without loading the whole file }

Q100.
What is the difference between PDO and MySQLi, and why might you prefer PDO?

Mid

Both are database extensions, but MySQLi works only with MySQL/MariaDB, whereas PDO is a database-agnostic abstraction layer supporting many drivers behind one API. PDO is usually preferred for its portability, consistent interface, and clean named-parameter prepared statements.

  • Database support:

    • MySQLi: MySQL only.

    • PDO: 12+ drivers (MySQL, PostgreSQL, SQLite, SQL Server), so switching DB needs minimal code change.

  • API and parameter binding:

    • PDO supports both named (:id) and positional (?) placeholders; MySQLi supports only positional.

    • PDO offers a clean object-oriented API; MySQLi has both procedural and OO styles.

  • Both share key strengths: Prepared statements (preventing SQL injection), transactions, and stored procedures.

  • Where MySQLi edges ahead: Exposes some MySQL-specific features (async queries, certain server stats) that PDO abstracts away.

  • Prefer PDO for portability and a uniform interface; choose MySQLi only when you need MySQL-only features.

php

$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute(['id' => $id]); $user = $stmt->fetch(PDO::FETCH_ASSOC);

Q101.
What is the purpose of the try/catch/finally block, and how do you create custom exceptions in PHP?

Mid

try/catch/finally handles runtime errors gracefully: code that may fail goes in try, matching exceptions are handled in catch, and finally always runs for cleanup. Custom exceptions are just classes extending Exception (or a more specific base).

  • try: Wraps code that might throw; execution jumps to a matching catch the moment an exception is thrown.

  • catch: Matches by exception type; order specific to general, and you can catch multiple types with catch (TypeA | TypeB $e).

  • finally: Always executes (exception or not), even after a return; ideal for releasing resources (files, locks, connections).

  • Custom exceptions:

    • Extend Exception (or RuntimeException, etc.) to create meaningful, catchable types for your domain.

    • Lets callers catch precisely (catch PaymentFailedException without swallowing everything).

php

class InsufficientFundsException extends \RuntimeException {} try { $account->withdraw($amount); } catch (InsufficientFundsException $e) { log_error($e->getMessage()); } finally { $account->unlock(); // always runs }

Q102.
How do you internationalize and handle character encoding (UTF-8, multibyte strings) in PHP?

Mid

PHP strings are byte sequences with no inherent encoding, so for international text you standardize on UTF-8 end to end and use the mbstring functions for any length/case/substring work, plus the intl extension for locale-aware formatting and translation files for the actual messages.

  • Use multibyte string functions:

    • strlen(), substr(), strtoupper() count bytes and corrupt multibyte chars; use mb_strlen(), mb_substr(), mb_strtoupper() with an explicit UTF-8 encoding.

    • Set mb_internal_encoding('UTF-8') once.

  • Keep encoding consistent across boundaries:

    • Save source files as UTF-8, set DB/connection charset to utf8mb4, and send Content-Type: text/html; charset=UTF-8.

    • Convert untrusted input with mb_convert_encoding() and validate via mb_check_encoding().

  • Locale-aware formatting with intl: NumberFormatter, IntlDateFormatter, and Collator handle currency, dates, and correct sorting per locale.

  • Translating messages: gettext or a framework's translation component maps message keys to locale files; never concatenate translated fragments.

Q103.
Discuss the trade-offs of using readonly classes versus traditional private properties with getters.

Senior

A readonly class enforces immutability at the language level (properties can only be set once during initialization), while private properties with getters give you encapsulation plus the flexibility to compute, lazily load, or later mutate values.

  • readonly advantages:

    • Guaranteed immutability without writing defensive getters; ideal for value objects and DTOs.

    • Less boilerplate and intent is explicit in the declaration.

    • Properties can stay public yet remain safe from external mutation.

  • readonly trade-offs:

    • No transformation layer: a getter can change return type or format internally without breaking callers, a public readonly property cannot.

    • To 'change' a value you must clone with clone/withers, which can feel heavy.

    • Cannot be lazily computed or cached after construction.

  • Getters' advantage: Encapsulation lets internal representation evolve independently of the public API (a key OOP principle).

  • Rule of thumb: Use readonly for simple immutable data; use private + getters when you need computed values or API stability over a changing representation.

Q104.
What are Property Hooks (introduced in PHP 8.4), and what problem do they solve regarding getters and setters?

Senior

Property Hooks let you attach get and set logic directly to a property declaration, so you get computed or validated values without writing separate getter and setter methods or breaking the natural $obj->prop access syntax.

  • The problem they solve: Traditionally you either expose a public property (no control) or write private property + getX()/setX() boilerplate, changing how callers access it.

  • How hooks work:

    • You define behavior inline; a get hook can compute a value and a set hook can validate or transform before storing.

    • Callers still use simple property syntax, while logic runs behind the scenes.

  • Benefits: Less boilerplate, encapsulation without changing the public API, and a property can be virtual (no backing storage).

php

class User { public string $name { set => ucfirst($value); } public string $fullName { get => $this->first . ' ' . $this->last; } }

Q105.
What are Property Hooks in PHP 8.4, and how do they change the traditional getter/setter pattern?

Senior

Property Hooks let you attach get and set logic directly to a property declaration, so computed or validated values no longer require separate getter/setter methods plus a backing property.

  • What they are:

    • Inline behavior defined on the property itself using a get and/or set block.

    • Callers still access $obj->name naturally: the hook runs transparently.

  • How they change getters/setters:

    • No more boilerplate getName()/setName() pairs plus a private field.

    • Validation, normalization, and computed values live next to the property.

    • A property can be virtual: a get hook with no backing storage computes its value on read.

  • Caveat: Inside a hook you reference the backing store via the property name itself; accessing it within its own get without care can recurse.

php

class User { public string $name { get => ucfirst($this->name); set => strtolower($value); } // Virtual property: no backing field public string $fullName { get => $this->first . ' ' . $this->last; } }

Q106.
Explain 'Asymmetric Visibility' introduced in PHP 8.4. When would you use private(set)?

Senior

Asymmetric Visibility lets a property be read with one visibility but written with a stricter one, so you can expose a value publicly while restricting who can change it.

  • Syntax:

    • Declare the read scope normally and the write scope in parentheses: public private(set) int $id;.

    • The set scope must be equal to or more restrictive than the get scope.

  • When to use private(set):

    • Read-only-to-the-outside, mutable-internally values: an $id or $status the class manages but callers only read.

    • Like readonly but the class can still reassign it after construction.

  • Benefit: Removes the need for a public getter just to protect a field from external writes.

php

class Order { public private(set) string $status = 'pending'; public function ship(): void { $this->status = 'shipped'; // allowed inside the class } } $o = new Order(); echo $o->status; // readable $o->status = 'x'; // Error: write is private

Q107.
What is the benefit of 'Typed Class Constants' introduced in PHP 8.3?

Senior

Typed Class Constants let you declare an explicit type on a constant, enforcing that the value (and any overriding value in subclasses) matches that type.

  • What it solves:

    • Previously a constant's type was implicit and a child class could redeclare it with a different type silently.

    • Now const string FOO = 'x'; is enforced, including on inheritance.

  • Benefits:

    • Catches type mismatches at compile time rather than at runtime.

    • Documents intent and improves IDE and static-analysis accuracy.

    • Works on class, interface, and enum constants.

php

interface HasVersion { const string VERSION = '1.0'; } class App implements HasVersion { const string VERSION = 2; // TypeError: must be string }

Q108.
How does the json_validate() function in PHP 8.3 improve performance compared to json_decode()?

Senior

json_validate() checks whether a string is valid JSON without building the resulting PHP data structure, so it uses far less memory and time than calling json_decode() just to test validity.

  • The old pattern was wasteful: Developers called json_decode() and checked json_last_error(), which allocates the entire decoded structure even when you only need a yes/no.

  • Why json_validate() is faster:

    • It parses the input but never materializes arrays/objects, so memory stays low on large payloads.

    • Returns a simple bool.

  • When to use:

    • Validating untrusted input before you actually need the data, or rejecting bad requests early.

    • If you need the data anyway, just decode once: don't validate then decode.

php

if (json_validate($payload)) { $data = json_decode($payload, true); }

Q109.
Explain the concept of 'Ghost Objects' (Lazy Objects) in PHP 8.4 and their use case in ORMs.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q110.
What are 'Readonly Classes' in PHP 8.2, and why can't they contain non-readonly properties?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q111.
What is the difference between the JIT compiler and OpCache? Does JIT always improve performance?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q112.
What are Property Hooks in PHP 8.4 and how do they change the way we write getters and setters?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q113.
Explain the concept of 'Asymmetric Visibility' introduced in PHP 8.4. When would you use it?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q114.
Explain 'DNF Types' (Disjunctive Normal Form) introduced in PHP 8.2. How do they allow for more complex type hinting?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q115.
What is the 'Repository Pattern,' and why do some developers argue it is redundant when using Laravel's Eloquent ORM?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q116.
Explain the 'Facade' pattern in PHP. What are the trade-offs between using Facades versus Dependency Injection?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q117.
Explain 'Late Static Binding' and the difference between self:: and static::.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q118.
What are the architectural implications of using 'Final' classes by default in a large-scale application?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q119.
Explain the 'Type Juggling' vulnerabilities and how strict typing (declare(strict_types=1)) mitigates specific security risks.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q120.
Explain the concept of 'SQL Injection' in the context of PHP's PDO. How do prepared statements actually prevent it at the protocol level?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q121.
What is the difference between self:: and static:: when calling a method or property in an inherited class?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q122.
How does PHP-FPM work, and how does it interact with a web server like Nginx?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q123.
Explain the PHP request lifecycle from the moment a request hits the server to the moment it is terminated.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q124.
Explain the difference between Thread Safe (TS) and Non-Thread Safe (NTS) versions of PHP.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q125.
Explain the lifecycle of a PHP request when running under PHP-FPM and Nginx.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q126.
Explain 'Type Juggling' in PHP. Why is it considered a security risk in certain contexts?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q127.
What are the tradeoffs of using a heavy framework like Laravel versus building a 'frameworkless' or 'vanilla' PHP application?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q128.
Why is PHP often criticized for its scalability, and how would you argue against that notion in a modern context?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q129.
How does the PHP Garbage Collector work, specifically regarding circular references?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q130.
How would you identify and debug a memory leak in a long-running PHP CLI script or worker?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q131.
How does PHP's garbage collection work, and how does it handle circular references?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q132.
How does PHP's Garbage Collector handle circular references, and what is the role of the 'Cyclic Garbage Collector'?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q133.
How does the PHP Garbage Collector handle circular references, and when does it actually trigger?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q134.
What is the JIT (Just-In-Time) compiler in PHP 8, and in what specific scenarios does it provide a performance boost?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q135.
How does OPcache improve performance, and what are the risks of 'stale' code in a production environment?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q136.
What is the Just-In-Time (JIT) compiler in PHP 8, and for what types of applications does it provide the most significant performance boost?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q137.
How would you optimize a PHP application that is experiencing high memory usage or slow response times?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q138.
What are PHP Fibers, and how do they enable 'green threading' or concurrency without being true multi-threading?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q139.
Why is PHP traditionally not 'async' by default, and what are the tradeoffs of using tools like Swoole or RoadRunner to achieve concurrency?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q140.
What are Fibers in PHP, and how do they enable 'cooperative multitasking' without being true threads?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q141.
How do Fibers in PHP 8.1 facilitate cooperative multitasking, and how do they differ from true multi-threading?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q142.
What is the internal difference between an Array and a SplFixedArray in terms of memory and performance?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q143.
How does the Zend Engine's Hash Table implementation allow PHP arrays to function as both lists and associative maps?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q144.
What are PHP iterators and the Iterator/IteratorAggregate interfaces used for?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.