PHP

PHP Q&A (Beginner - Advanced)

Beginner Level (Q1-Q60)

Q1: What is PHP?

PHP is a server-side scripting language used to build dynamic web apps. It processes requests on the server and returns HTML, JSON, or other responses.

Q2: Why is PHP popular?

PHP is easy to start, widely hosted, and has a huge ecosystem (Laravel, WordPress, etc.). It balances developer productivity, community support, and practical web performance.

Q3: How do you start a PHP script?

A PHP script starts with <?php. In pure PHP files, the closing tag ?> is usually omitted to prevent accidental output.

Q4: How do you print output in PHP?

Use echo (most common) or print. Both output text; echo is slightly more flexible and commonly preferred.

Q5: How are variables declared?

Variables begin with $ and are dynamically typed. Type depends on assigned value and can change later.

Q6: Is PHP strongly typed?

Traditionally dynamic, but modern PHP supports strong typing features. Type hints, return types, unions, and strict mode improve safety.

Q7: What is declare(strict_types=1);?

It enables strict scalar type checking in that file. Without it, PHP may coerce values between scalar types.

Q8: What are PHP scalar types?

The scalar types are int, float, string, and bool. These are the basic single-value primitives in PHP.

Q9: What are compound types?

Compound types include array, object, callable, and iterable. They represent structured or executable data forms.

Q10: What are special types?

Special types include null, resource, mixed, void, and never. They model absence, generic values, non-returning functions, and runtime handles.

Example (Q1-Q10)

<?php
declare(strict_types=1);

function greet(string $name): string {
    return "Hello, $name";
}

echo greet("Anna") . PHP_EOL;

Q11: How do strings work in PHP?

Single-quoted strings are mostly literal. Double-quoted strings support interpolation and escape sequences.

Q12: How do you concatenate strings?

Use the dot operator (.) to join strings. This is the standard PHP string concatenation syntax.

Q13: What is variable interpolation?

In double-quoted strings, variables are expanded automatically. It improves readability for simple dynamic strings.

Q14: How do comments work?

Use // or # for single-line comments. Use /* ... */ for block comments.

Q15: What are constants?

Constants are immutable values defined with const or define(). They are used for fixed app-wide configuration values.

Q16: Difference between define and const?

const is language-level and preferred in modern code. define() is runtime-based and useful in dynamic scenarios.

Q17: Difference between == and ===?

== compares values with type juggling. === compares both value and type strictly.

Q18: Why prefer ===?

Strict comparison avoids unexpected coercion bugs. It makes conditions safer and easier to reason about.

Q19: What is truthy/falsy in PHP?

Values like 0, "0", "", [], null, false are falsy. Most other non-empty/non-zero values are truthy.

Q20: How does if/elseif/else work?

Conditions are evaluated top-down. The first true branch executes; otherwise else runs.

Example (Q11-Q20)

<?php
$value = "0";

if ($value == 0) {
    echo "Loose comparison true\n";
}

if ($value === 0) {
    echo "Strict comparison true\n";
} else {
    echo "Strict comparison false\n";
}

Q21: What is switch?

switch selects code branch based on expression matching. Historically it uses loose comparison behavior.

Q22: What is match in modern PHP?

match is an expression with strict matching and returned result. It is safer and avoids accidental fall-through.

Q23: What loops are available?

PHP provides for, while, do...while, and foreach. Choose based on counter-based vs collection-based iteration needs.

Q24: When to use foreach?

Use foreach for arrays and Traversable objects. It is cleaner and less error-prone than manual index loops.

Q25: What does break do?

break immediately exits the nearest loop or switch. Useful when target condition is achieved early.

Q26: What does continue do?

continue skips current iteration and moves to next one. Useful for ignoring unwanted items quickly.

Q27: What is an array in PHP?

A PHP array is an ordered map (key-value structure). It can behave like list, dictionary, stack, and more.

Q28: Indexed vs associative arrays?

Indexed arrays use numeric keys. Associative arrays use string keys for named access.

Q29: How to check if key exists in array?

Use array_key_exists("key", $arr). It detects key presence even when value is null.

Q30: isset vs array_key_exists?

isset($arr['k']) is false for missing keys and null values. array_key_exists('k', $arr) is true if key exists regardless of null.

Example (Q21-Q30)

<?php
$user = ["name" => "Sam", "age" => null];

var_dump(isset($user["age"])); // false
var_dump(array_key_exists("age", $user)); // true

$status = 200;
$message = match ($status) {
    200 => "OK",
    404 => "Not Found",
    default => "Unknown"
};

echo $message . PHP_EOL;

Q31: How do you sort arrays?

Use sort helpers like sort, asort, ksort, usort based on needs. Pick value sort vs key sort and stable custom comparator carefully.

Q32: What is a function?

A function is reusable logic with inputs and optional return value. It improves modularity and avoids repetition.

Q33: What are default parameters?

Default parameters provide fallback values if argument is omitted. They simplify function calls for common cases.

Q34: What is a return type declaration?

It defines the expected output type of a function. This improves correctness and readability.

Q35: What are nullable types?

?Type means the value may be Type or null. Useful when absence is a valid result.

Q36: What are union types?

Union types allow multiple accepted types (e.g., int|string). They model flexible but explicit contracts.

Q37: What are named arguments?

Named arguments pass values by parameter name. They improve clarity, especially with many optional params.

Q38: What is variadic argument list?

Variadics (...$args) collect variable number of arguments. Useful for flexible APIs and wrappers.

Q39: What are superglobals?

Superglobals are built-in global arrays available everywhere. Examples: $_GET, $_POST, $_SERVER, $_SESSION.

Q40: What is $_GET?

$_GET contains URL query parameters. Use validation before trusting its values.

Example (Q31-Q40)

<?php
function sum(int ...$nums): int {
    return array_sum($nums);
}
echo sum(1, 2, 3, 4) . PHP_EOL;

function greet(string $name = "Guest"): string {
    return "Hi, $name";
}
echo greet() . PHP_EOL;

Q41: What is $_POST?

$_POST contains request body fields from POST forms. Treat all incoming data as untrusted input.

Q42: What is $_REQUEST?

$_REQUEST combines GET/POST/COOKIE depending on configuration. Prefer explicit sources ($_GET or $_POST) for clarity and safety.

Q43: How to safely read input?

Validate expected format and sanitize when needed. Reject invalid input early and escape on output.

Q44: What is filter_var used for?

filter_var validates/sanitizes common values like email and URL. It provides standardized input checks.

Q45: What is htmlspecialchars for?

Escapes special HTML chars to prevent script injection. Core output-escaping defense against XSS.

Q46: What is XSS?

XSS is script injection into trusted web pages. It can steal sessions, deface UI, or run malicious actions.

Q47: How to prevent XSS?

Use context-aware escaping and secure templating defaults. Add CSP and never render raw untrusted HTML.

Q48: What is CSRF?

CSRF forces authenticated users to send unintended actions. Attack exploits browser auto-sent credentials.

Q49: How to prevent CSRF?

Use anti-CSRF tokens and SameSite cookies. Optionally verify Origin/Referer for sensitive endpoints.

Q50: What are sessions?

Sessions store user state on the server across requests. Client keeps only a session identifier cookie.

Example (Q41-Q50)

<?php
session_start();

$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
if ($email === false) {
    echo "Invalid email";
    exit;
}

echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8');

Q51: How to start a session?

Call session_start() before any output is sent. Then read/write $_SESSION safely.

Q52: What are cookies?

Cookies are small client-stored key/value data. Browser sends them automatically with matching requests.

Q53: How to set cookie?

Use setcookie() with options like secure, httponly, samesite. Avoid storing sensitive raw data in cookies.

Q54: What is file inclusion?

Including loads and executes another PHP file. Used for shared templates, config, and reusable modules.

Q55: include vs require?

include gives warning if file missing; execution may continue. require gives fatal error; execution stops.

Q56: Purpose of include_once?

Ensures the same file is included only once. Prevents redeclaration errors and duplicate side effects.

Q57: How to read file content?

Use file_get_contents() for straightforward file reads. For large files, prefer streaming line by line.

Q58: How to write file content?

Use file_put_contents() for simple writes. Use append/lock flags when needed to avoid race issues.

Q59: How to check if file exists?

Use file_exists("path"). Also validate readability/writability for robust handling.

Q60: How to handle date/time?

Use DateTimeImmutable with explicit timezone. Avoid raw string math for reliable date operations.

Example (Q51-Q60)

<?php
date_default_timezone_set('UTC');

$now = new DateTimeImmutable('now');
echo $now->format(DateTimeInterface::ATOM) . PHP_EOL;

setcookie('theme', 'dark', [
    'expires' => time() + 3600,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

Intermediate Level (Q61-Q120)

Q61: What is OOP in PHP?

OOP organizes code using classes and objects to model real-world behavior. It improves maintainability, reuse, and testability in medium/large applications.

Q62: What is a class?

A class is a blueprint that defines properties and methods. Objects are created from classes as usable runtime instances.

Q63: What is an object?

An object is an instance of a class with its own state. Multiple objects of one class can hold different data.

Q64: What is a constructor?

__construct() runs automatically when an object is created. It is used to initialize required dependencies or default state.

Q65: What is a destructor?

__destruct() runs when an object is about to be destroyed. It can release resources, though explicit cleanup is often preferred.

Q66: Access modifiers?

public is accessible everywhere, protected in class/subclasses, private only in same class. They enforce encapsulation and control object internals safely.

Q67: What is inheritance?

Inheritance lets a child class reuse/extend parent behavior via extends. Use it for true “is-a” relationships, not just code sharing.

Q68: What is method overriding?

A child class can redefine an inherited method with its own implementation. This enables polymorphic behavior for specialized logic.

Q69: What is final keyword?

final class cannot be extended; final method cannot be overridden. Use it to protect critical behavior/contracts from alteration.

Q70: What is an abstract class?

An abstract class cannot be instantiated directly. It provides shared base logic and may force subclasses to implement abstract methods.

Example (Q61-Q70)

<?php
abstract class Animal {
    public function __construct(protected string $name) {}
    abstract public function speak(): string;
}

final class Dog extends Animal {
    public function speak(): string {
        return "{$this->name} says woof";
    }
}

$dog = new Dog("Max");
echo $dog->speak() . PHP_EOL;

Q71: What is an interface?

An interface defines method signatures without implementation. Classes implementing it must provide all declared methods.

Q72: Interface vs abstract class?

Interface is a pure contract; abstract class can include shared code/state. Use interfaces for capabilities, abstract classes for common base behavior.

Q73: What are traits?

Traits allow horizontal code reuse across unrelated classes. They reduce duplication when inheritance is not appropriate.

Q74: What is encapsulation?

Encapsulation hides internal state and exposes controlled methods. It prevents invalid object states and accidental external mutation.

Q75: What is polymorphism?

Polymorphism allows different classes to be used via a common interface/type. Caller code stays generic while implementations vary.

Q76: What are static properties/methods?

Static members belong to the class, not object instances. Use for shared utility/state carefully to avoid global-coupling issues.

Q77: What does $this mean?

$this refers to the current object instance inside non-static methods. It gives access to instance properties and methods.

Q78: What is late static binding?

static:: resolves to the called class at runtime in inheritance chains. It enables inherited methods to instantiate/use subclass context correctly.

Q79: What are magic methods?

Special methods like __get, __set, __call, __toString hook object behavior. Use carefully—they are powerful but can hide complexity.

Q80: What is autoloading?

Autoloading loads class files automatically when referenced. Composer PSR-4 autoload is the standard approach in modern PHP projects.

Example (Q71-Q80)

<?php
interface Logger {
    public function log(string $msg): void;
}

trait TimestampTrait {
    private function now(): string { return date('c'); }
}

class FileLogger implements Logger {
    use TimestampTrait;

    public function log(string $msg): void {
        echo "[{$this->now()}] $msg" . PHP_EOL;
    }
}

$logger = new FileLogger();
$logger->log("Application started");

Q81: What is Composer?

Composer is PHP’s dependency manager and autoload generator. It installs packages, resolves versions, and standardizes project setup.

Q82: What is composer.json?

It is the project manifest describing dependencies, scripts, and autoload config. It is the central file for package and build behavior.

Q83: What is PSR?

PSR means PHP Standards Recommendations from PHP-FIG. They improve code consistency and library interoperability.

Q84: What is PSR-4?

PSR-4 maps namespaces to directory paths for autoloading. It removes manual include/require for class files.

Q85: What is namespace?

A namespace isolates symbols (classes/functions/constants) to avoid naming conflicts. It is essential in larger projects and package ecosystems.

Q86: How to import classes?

Use use Vendor\Package\ClassName; at file top. You can alias long names with as for readability.

Q87: What are exceptions?

Exceptions are objects representing runtime error conditions. They separate normal flow from failure-handling flow.

Q88: try/catch/finally meaning?

try runs risky code, catch handles thrown exceptions. finally always runs, usually for cleanup.

Q89: Why throw custom exceptions?

Custom exceptions express domain-specific failures clearly. They make error handling more intentional and meaningful.

Q90: Error vs Exception in PHP?

Both implement Throwable; Exception is for application-level failures. Error generally represents engine/type/runtime programming issues.

Example (Q81-Q90)

<?php
class InvalidOrderException extends RuntimeException {}

function placeOrder(int $qty): void {
    if ($qty <= 0) {
        throw new InvalidOrderException("Quantity must be > 0");
    }
    echo "Order placed: $qty" . PHP_EOL;
}

try {
    placeOrder(0);
} catch (InvalidOrderException $e) {
    echo "Order error: " . $e->getMessage() . PHP_EOL;
} finally {
    echo "Done." . PHP_EOL;
}

Q91: How to connect to MySQL safely?

Use PDO with exception mode and prepared statements. Never build SQL by concatenating raw user input.

Q92: Why use PDO over old mysql extension?

Old mysql extension is removed and insecure by modern standards. PDO supports prepared statements and multiple databases consistently.

Q93: What is a prepared statement?

A prepared statement compiles SQL with placeholders first. Input values are bound separately, preventing SQL injection.

Q94: What is SQL injection?

SQL injection is malicious input altering intended SQL query logic. It can expose, modify, or delete sensitive database data.

Q95: How to prevent SQL injection?

Use parameterized queries everywhere. Also apply validation and least-privilege DB accounts.

Q96: How to fetch DB rows in PDO?

Use fetch() for one row or fetchAll() for multiple rows. Set fetch mode (e.g., PDO::FETCH_ASSOC) for predictable structure.

Q97: What is transaction?

A transaction groups operations as one atomic unit. Either all succeed (commit) or all are undone (rollBack).

Q98: PDO transaction methods?

Use beginTransaction(), commit(), and rollBack(). Wrap multi-step critical writes to keep data consistent.

Q99: Password hashing best practice?

Use password_hash() and verify with password_verify(). Never store plaintext or use weak hashes like raw MD5/SHA1.

Q100: Why not store plain passwords?

Database leaks become immediate account compromise. Hashed passwords significantly reduce attacker success.

Example (Q91-Q100)

<?php
$pdo = new PDO(
    "mysql:host=localhost;dbname=test;charset=utf8mb4",
    "user",
    "pass",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$email = "sam@example.com";
$stmt = $pdo->prepare("SELECT id, password_hash FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify("secret123", $user['password_hash'])) {
    echo "Login success" . PHP_EOL;
}

Q101: How to verify password?

Use password_verify($plain, $hash). It safely compares plaintext against the stored hash.

Q102: What is REST?

REST is an architectural style for resource-based HTTP APIs. It uses standard methods and stateless communication patterns.

Q103: Common HTTP methods in APIs?

GET (read), POST (create), PUT/PATCH (update), DELETE (remove). Method semantics improve API consistency and client understanding.

Q104: Common API status codes?

Common codes: 200, 201, 204, 400, 401, 403, 404, 409, 422, 500. Choose accurate status codes to communicate outcome clearly.

Q105: How to return JSON response?

Set Content-Type: application/json header. Encode payload with json_encode() (prefer throw-on-error mode).

Q106: What is JSON encoding error handling?

Use JSON_THROW_ON_ERROR to avoid silent failures. Catch JsonException and return controlled error response.

Q107: What is middleware in PHP frameworks?

Middleware is a request/response pipeline layer. It handles cross-cutting concerns like auth, logging, and rate limits.

Q108: What is routing?

Routing maps HTTP method/path to handler/controller action. It is the entry-point dispatch mechanism of web apps.

Q109: What is MVC pattern?

Model handles data/domain, View handles presentation, Controller coordinates flow. It separates concerns for cleaner organization.

Q110: What is ORM?

ORM maps database tables to objects/entities. It speeds development but requires query-awareness for performance.

Example (Q101-Q110)

<?php
header('Content-Type: application/json');

try {
    $data = ['status' => 'ok', 'time' => date('c')];
    echo json_encode($data, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'JSON encode failed']);
}

Q111: Benefits of ORM?

ORM improves productivity with models, relations, and abstractions. But developers must still understand SQL/performance trade-offs.

Q112: What is N+1 query problem?

It occurs when one query loads items, then one extra query per item runs. This creates major latency and DB load at scale.

Q113: How to avoid N+1?

Use eager loading, joins, or batching strategies. Always profile query counts on list endpoints.

Q114: What is caching?

Caching stores computed/fetched data for faster repeated access. It reduces DB hits, CPU work, and response time.

Q115: Types of cache in PHP apps?

Common types: OPcache, app cache (Redis/Memcached), HTTP cache. Different layers solve different latency bottlenecks.

Q116: What is OPcache?

OPcache stores compiled PHP bytecode in memory. It avoids recompiling scripts on each request.

Q117: What is logging best practice?

Write structured logs with context (requestid, userid, level). Never log secrets, tokens, or sensitive personal data.

Q118: What is dependency injection?

Dependency injection provides collaborators from outside the class. It reduces coupling and improves testability.

Q119: Why dependency injection?

DI makes components easier to replace/mock. It supports clean architecture and modular design.

Q120: What is inversion of control container?

An IoC container resolves and wires object dependencies automatically. Frameworks use it to manage lifecycle and configuration centrally.

Example (Q111-Q120)

<?php
interface Mailer { public function send(string $to, string $msg): void; }

class SmtpMailer implements Mailer {
    public function send(string $to, string $msg): void {
        echo "Sending to $to: $msg" . PHP_EOL;
    }
}

class UserService {
    public function __construct(private Mailer $mailer) {}
    public function welcome(string $email): void {
        $this->mailer->send($email, "Welcome!");
    }
}

$service = new UserService(new SmtpMailer());
$service->welcome("anna@example.com");

Advanced Level (Q121-Q160)

Q121: What is SOLID in PHP design?

SOLID is a set of five OOP principles for maintainable, extensible systems. It reduces tight coupling and makes code easier to test and evolve.

Q122: Explain SRP.

Single Responsibility Principle means a class should have one reason to change. Each class should focus on one clear responsibility.

Q123: Explain OCP.

Open/Closed Principle: software entities should be open for extension. But they should be closed for direct modification of stable behavior.

Q124: Explain LSP.

Liskov Substitution Principle says subtypes must replace base types safely. Child classes must honor parent contracts and expectations.

Q125: Explain ISP.

Interface Segregation Principle prefers small, focused interfaces. Clients should not depend on methods they do not use.

Q126: Explain DIP.

Dependency Inversion Principle: depend on abstractions, not concrete classes. High-level policy and low-level details should both rely on interfaces.

Q127: Design patterns often used in PHP?

Common patterns include Factory, Strategy, Repository, Adapter, Decorator, Observer, Builder. Patterns provide proven templates for recurring design problems.

Q128: Factory pattern in brief?

Factory encapsulates object creation logic behind a clear API. It hides construction complexity and improves flexibility.

Q129: Strategy pattern in brief?

Strategy wraps interchangeable algorithms behind one interface. You can swap behavior at runtime without changing caller code.

Q130: Repository pattern in brief?

Repository abstracts persistence behind domain-friendly operations. It isolates data access details from business logic.

Example (Q121-Q130)

<?php
interface DiscountStrategy { public function apply(float $amount): float; }

class NoDiscount implements DiscountStrategy {
    public function apply(float $amount): float { return $amount; }
}
class TenPercentDiscount implements DiscountStrategy {
    public function apply(float $amount): float { return $amount * 0.9; }
}

class CheckoutService {
    public function __construct(private DiscountStrategy $strategy) {}
    public function total(float $amount): float { return $this->strategy->apply($amount); }
}

echo (new CheckoutService(new TenPercentDiscount()))->total(100) . PHP_EOL; // 90

Q131: What is DTO?

DTO (Data Transfer Object) carries structured data between layers. It holds data only, usually without business behavior.

Q132: What is value object?

A value object is immutable and defined by its value, not identity. Two value objects with same values are considered equal logically.

Q133: Why immutability matters?

Immutability prevents accidental state changes and side effects. It improves reasoning, concurrency safety, and debugging.

Q134: What are closures?

Closures are anonymous functions that can be assigned or passed around. They are useful for callbacks, pipelines, and functional-style code.

Q135: What does use in closures do?

use imports variables from outer scope into a closure. It allows controlled variable capture for deferred execution.

Q136: What are generators?

Generators use yield to produce values lazily over time. They reduce memory usage when processing large datasets.

Q137: When to use generators?

Use generators for streaming large files/records incrementally. They avoid loading entire data into memory at once.

Q138: What is iterable type?

iterable accepts arrays and Traversable objects. It is useful for APIs that consume loopable data sources.

Q139: What is Traversable?

Traversable is the base internal interface for iterable objects. Custom iterables typically implement Iterator or IteratorAggregate.

Q140: What is ArrayAccess?

ArrayAccess allows objects to be accessed using array syntax. It enables \$obj['key'] behavior with custom logic.

Example (Q131-Q140)

<?php
final class Email {
    public function __construct(public readonly string $value) {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException("Invalid email");
        }
    }
}

function numbers(): Generator {
    for ($i = 1; $i <= 3; $i++) yield $i;
}

foreach (numbers() as $n) echo $n . PHP_EOL;

Q141: What is SPL in PHP?

SPL is the Standard PHP Library with core interfaces/classes. It includes iterators, data structures, exceptions, and utility tools.

Q142: What is serialization?

Serialization converts data/object state into storable/transmittable format. It is used for caching, transport, or persistence scenarios.

Q143: serialize/unserialize caveats?

Unserializing untrusted input is dangerous and can enable object injection. Avoid using it with external data sources.

Q144: Safer alternatives for data exchange?

Use JSON for public/external data exchange whenever possible. Use signed/encrypted tokens when integrity/confidentiality is required.

Q145: What is object injection vulnerability?

It exploits unsafe deserialization to trigger malicious object behavior. Attackers abuse magic methods and gadget chains in loaded classes.

Q146: What is command injection?

Command injection occurs when user input reaches shell commands unsafely. It can lead to arbitrary command execution on the server.

Q147: How to mitigate command injection?

Avoid shell execution when possible; use safe native APIs. If unavoidable, strict allowlists + escaping + least privilege are essential.

Q148: What is file inclusion vulnerability?

LFI/RFI happens when untrusted input controls included file paths. It can expose files or execute unintended code paths.

Q149: How to prevent LFI/RFI?

Never include files directly from raw user input. Use fixed maps/allowlists and keep remote includes disabled.

Q150: How to secure file uploads?

Validate MIME/signature/size/extension and randomize filenames. Store outside web root and scan uploads before processing.

Example (Q141-Q150)

<?php
$allowed = ['report' => '/var/app/templates/report.php'];
$key = $_GET['tpl'] ?? '';

if (!array_key_exists($key, $allowed)) {
    http_response_code(400);
    exit('Invalid template');
}

require $allowed[$key]; // allowlist-based include

Q151: HTTP security headers to know?

Important headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy. They reduce browser-side attack surface significantly.

Q152: What is CORS?

CORS is a browser policy controlling cross-origin resource access. Server response headers decide which origins/methods are allowed.

Q153: CORS best practice?

Use explicit trusted origin allowlists and minimal methods/headers. Do not use wildcard origin with credentialed requests.

Q154: What is rate limiting?

Rate limiting restricts request volume per client/window. It protects APIs from abuse, brute force, and overload.

Q155: What is idempotency?

Idempotency means repeated same request has same final effect. Critical for safe retries in unreliable networks.

Q156: What is optimistic locking?

Optimistic locking checks version/timestamp before update. If version changed, update fails and client retries/merges.

Q157: What is pessimistic locking?

Pessimistic locking acquires DB locks during transaction. It prevents concurrent conflicting writes but can reduce throughput.

Q158: What is eventual consistency?

Eventual consistency means replicas may temporarily diverge. Given time and no new writes, they converge to same state.

Q159: What are queues in PHP systems?

Queues move slow tasks (emails, exports, image processing) to background workers. They improve request latency and system resilience.

Q160: Queue reliability concerns?

Handle retries, dead-letter queues, idempotency, and visibility timeouts. Add monitoring/alerting to detect stuck or failing jobs.

Example (Q151-Q160)

<?php
// Idempotency example (conceptual)
$idempotencyKey = $_SERVER['HTTP_IDEMPOTENCY_KEY'] ?? null;
if (!$idempotencyKey) {
    http_response_code(400);
    exit('Missing Idempotency-Key');
}

// pseudo-store check
// if key already processed => return previous response
// else process payment, store result by key, return success

header('Content-Type: application/json');
echo json_encode(['status' => 'processed', 'key' => $idempotencyKey], JSON_THROW_ON_ERROR);

Expert Level (Q161-Q180)

Q161: How does PHP-FPM architecture work?

A web server (Nginx/Apache) forwards PHP requests to PHP-FPM worker pools. Workers execute scripts and return responses; pool sizing strongly affects latency and throughput.

Q162: Key PHP-FPM tuning parameters?

Important settings: pm, pm.max_children, pm.max_requests, request_terminate_timeout, memory limits. Tune them based on traffic profile, script memory usage, and CPU capacity.

Q163: Horizontal vs vertical scaling for PHP apps?

Vertical scaling increases resources on one server; simpler but has hard limits. Horizontal scaling adds instances behind a load balancer; better resilience and growth.

Q164: Stateless app design importance?

Stateless services make horizontal scaling and failover easy. Store session/state in shared systems (Redis/DB), not local process memory.

Q165: What is zero-downtime deployment in PHP?

Deploy without user-visible interruption using rolling/blue-green/canary strategies. Use health checks, atomic release switch, and fast rollback paths.

Q166: Migration safety in production?

Use backward-compatible, phased migrations that work across old/new app versions. Avoid long locks; add rollback plans and verify with production-like rehearsals.

Q167: How to manage secrets securely?

Use secret managers or environment injection, never commit secrets in code. Rotate keys regularly and audit access with least-privilege controls.

Q168: Observability pillars for PHP services?

The three pillars are logs, metrics, and traces. Together they answer what happened, how often, and where time was spent.

Q169: Useful PHP production metrics?

Track latency, error rate, throughput, saturation, DB latency, queue depth, and worker utilization. Use SLO-based dashboards and alert on symptom + cause indicators.

Q170: What is distributed tracing?

Tracing links spans across services using shared trace IDs. It reveals request path and bottlenecks across distributed systems.

Example (Q161-Q170)

<?php
// Minimal request timing + trace id example
$traceId = $_SERVER['HTTP_X_TRACE_ID'] ?? bin2hex(random_bytes(8));
$start = hrtime(true);

// ... handle request ...

$ms = (hrtime(true) - $start) / 1e6;
error_log(json_encode([
    'trace_id' => $traceId,
    'path' => $_SERVER['REQUEST_URI'] ?? '/',
    'latency_ms' => round($ms, 2),
    'level' => 'info'
], JSON_THROW_ON_ERROR));

Q171: How to profile PHP performance?

Use profilers/APM (e.g., Blackfire, Xdebug profiler, Datadog, New Relic). Profile real bottlenecks first, then optimize the most expensive paths.

Q172: Common PHP performance bottlenecks?

Typical issues: slow queries, N+1, heavy I/O, excessive serialization, cache misses. Also watch autoload overhead and large object graphs in hot paths.

Q173: What is bounded context (DDD) in PHP apps?

A bounded context is a clear domain boundary with its own language and model. It reduces accidental coupling and clarifies ownership between teams/modules.

Q174: Hexagonal architecture summary?

Keep domain logic at center; interact with external systems via ports/adapters. This improves testability and makes infrastructure replaceable.

Q175: What is CQRS?

CQRS separates write models (commands) from read models (queries). It improves scalability and clarity in complex, high-change domains.

Q176: Event sourcing in brief?

Store state changes as immutable events instead of current-state rows only. Current state is reconstructed by replaying event history.

Q177: Trade-offs of event sourcing?

Pros: full audit trail, temporal debugging, flexible projections. Cons: higher complexity, schema evolution burden, and tooling/ops overhead.

Q178: Backward compatibility strategy for public PHP APIs?

Use semantic versioning, explicit deprecation windows, and migration guides. Protect contracts with integration/contract tests and staged rollout policies.

Q179: How to design resilient integrations?

Use timeouts, retries with backoff + jitter, circuit breakers, and idempotency keys. Define fallback behavior and monitor dependency health continuously.

Q180: What defines expert-level PHP engineering?

Expertise means building secure, observable, scalable, maintainable systems. It combines strong design, delivery discipline, and production operational excellence.

Example (Q171-Q180)

<?php
interface PaymentGateway { public function charge(string $idempotencyKey, int $cents): bool; }

final class ResilientPaymentService {
    public function __construct(private PaymentGateway $gateway) {}

    public function chargeWithRetry(string $key, int $cents, int $maxAttempts = 3): bool {
        $attempt = 0;
        while (++$attempt <= $maxAttempts) {
            try {
                if ($this->gateway->charge($key, $cents)) return true;
            } catch (Throwable $e) {
                if ($attempt === $maxAttempts) throw $e;
                usleep((int)(100_000 * $attempt)); // simple backoff
            }
        }
        return false;
    }
}