Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

PHP

Interview questions & answers

Server-side scripting, Laravel-style topics, runtime.

102 questions

  1. Question 1

    What is PHP?

    A server-side scripting language embedded in HTML; executes on the server and outputs HTML. Common stacks: LAMP, Laravel/Symfony apps.

    Example code

    <?php
    echo "Hello, PHP\n";
  2. Question 2

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

    == compares with type juggling; === compares type and value. Prefer === to avoid surprising coercion.

    Example code

    <?php
    var_dump(0 == "0", 0 === "0");
  3. Question 3

    What are PHP superglobals?

    $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, $GLOBALS—built-in arrays for HTTP and runtime context.

    Example code

    <?php
    echo $_SERVER["REQUEST_METHOD"] ?? "CLI";
  4. Question 4

    include vs require?

    Both pull in files; require throws fatal error on failure, include emits warning. _once variants skip if already loaded.

    Example code

    <?php
    require_once __DIR__ . "/config.php";
  5. Question 5

    What is autoloading?

    spl_autoload_register or Composer PSR-4 maps class names to files so you don't manual require every class.

    Example code

    <?php
    spl_autoload_register(fn($c) => require str_replace("\\", "/", $c) . ".php");
  6. Question 6

    What is Composer?

    Dependency manager for PHP: composer.json declares packages; vendor/ and autoload.php wire class loading.

    Example code

    <?php
    // composer require vendor/autoload.php
  7. Question 7

    What is a namespace?

    Avoids class name collisions; use statement imports symbols. PSR-4 ties namespaces to directory paths.

    Example code

    <?php
    namespace App\Models;
    class User {}
  8. Question 8

    public, protected, private?

    Visibility for properties/methods: public anywhere, protected in class hierarchy, private to declaring class only.

    Example code

    <?php
    class A { public $x; protected $y; private $z; }
  9. Question 9

    static in PHP?

    Static properties/methods belong to the class, not instances. Late static binding uses static:: for overridden static calls.

    Example code

    <?php
    class B { public static $n = 0; }
  10. Question 10

    What are traits?

    Horizontal code reuse; compose behavior into classes when multiple inheritance isn't available.

    Example code

    <?php
    trait T { function hi() { echo "hi"; } }
    class C { use T; }
  11. Question 11

    Abstract class vs interface?

    Abstract class can hold state and partial implementation; interface is a pure contract. A class extends one abstract, implements many interfaces.

    Example code

    <?php
    interface I { public function m(): void; }
  12. Question 12

    What is PDO?

    Database abstraction layer with prepared statements; safer than raw concatenation for SQL injection prevention.

    Example code

    <?php
    $pdo = new PDO("sqlite::memory:");
    $st = $pdo->prepare("SELECT ?");
    $st->execute([1]);
  13. Question 13

    Prepared statements — why?

    Separate SQL from data; database binds parameters, blocking most injection and aiding query plan reuse.

    Example code

    <?php
    $st = $pdo->prepare("SELECT * FROM u WHERE id = :id");
    $st->execute([":id" => $id]);
  14. Question 14

    What is mysqli?

    MySQL-specific extension; can be procedural or OOP. PDO is preferred when supporting multiple DB vendors.

    Example code

    <?php
    $mysqli = new mysqli("127.0.0.1", "u", "p", "db");
  15. Question 15

    Sessions in PHP?

    session_start() ties a cookie (PHPSESSID) to server-side storage; $_SESSION persists per user across requests.

    Example code

    <?php
    session_start();
    $_SESSION["uid"] = 1;
  16. Question 16

    Cookies vs sessions?

    Cookies are client-stored small data; sessions store sensitive data server-side with only an ID in the cookie.

    Example code

    <?php
    setcookie("theme", "dark", ["httponly" => true, "samesite" => "Lax"]);
  17. Question 17

    What is htmlspecialchars?

    Escapes HTML special chars for output context—essential when echoing user input to prevent XSS.

    Example code

    <?php
    echo htmlspecialchars($userInput, ENT_QUOTES, "UTF-8");
  18. Question 18

    filter_var and validation?

    Built-in filters validate/sanitize emails, URLs, ints—first line of defense before business rules.

    Example code

    <?php
    $email = filter_var($s, FILTER_VALIDATE_EMAIL);
  19. Question 19

    What is OPcache?

    Bytecode cache in production PHP; avoids re-parsing on every request—huge win for throughput.

    Example code

    <?php
    // opcache.enable=1 in php.ini for production
  20. Question 20

    PHP-FPM?

    FastCGI Process Manager runs PHP workers behind nginx/Apache; pools, workers, and timeouts tune concurrency.

    Example code

    <?php
    // php-fpm pool pm.max_children tuning
  21. Question 21

    What is Laravel?

    Popular MVC framework: routing, Eloquent ORM, Blade, queues, scheduling—batteries included for web apps.

    Example code

    <?php
    // routes/web.php Route::get("/", fn() => view("home"));
  22. Question 22

    Eloquent ORM basics?

    Active-record style models; relationships (hasMany, belongsTo), migrations, and query builder fluent API.

    Example code

    <?php
    // User::with("posts")->get();
  23. Question 23

    Blade templates?

    Compiled to plain PHP; @if, @foreach, layouts/components—escape with {{ }} by default.

    Example code

    <?php
    // @foreach($items as $i) {{ $i->name }} @endforeach
  24. Question 24

    What is middleware?

    HTTP pipeline layers that inspect/modify request/response (auth, logging) before the controller.

    Example code

    <?php
    // $stack->push(new AuthMiddleware());
  25. Question 25

    What is Symfony?

    Component-based framework and full stack; HttpFoundation, DependencyInjection, used standalone or in Laravel pieces.

    Example code

    <?php
    // $container->bind(I::class, Impl::class);
  26. Question 26

    Dependency injection in PHP?

    Constructor injection of services/interfaces; containers (Laravel/Symfony) resolve concrete implementations.

    Example code

    <?php
    use Psr\Http\Message\ServerRequestInterface;
  27. Question 27

    What is PSR-7?

    HTTP message interfaces (Request/Response) enabling interoperable middleware and clients.

    Example code

    <?php
    // composer dump-autoload -o
  28. Question 28

    What is PSR-4?

    Autoloading standard mapping namespaces to directory structures—Composer's default.

    Example code

    <?php
    try { throw new Exception("x"); } catch (Exception $e) { echo $e->getMessage(); }
  29. Question 29

    Error vs Exception in PHP?

    Throwable base; Error for engine/type issues, Exception for catchable app errors. try/catch/finally handle Exceptions; errors differ by version/handler.

    Example code

    <?php
    function f(int $x): string { return (string)$x; }
  30. Question 30

    Type declarations?

    Scalar and return types (PHP 7+), union types, nullable ?, readonly properties (8.1+), enums (8.1)—modern PHP is strongly typed optionally.

    Example code

    <?php
    $a = null;
    echo $a ?? "default";
  31. Question 31

    What is null coalescing ??

    Returns left if set and not null, else right—cleaner than isset ternary chains.

    Example code

    <?php
    usort($a, fn($x, $y) => $x <=> $y);
  32. Question 32

    What is the spaceship operator <=>?

    Three-way compare returning -1, 0, 1—handy for usort callbacks.

    Example code

    <?php
    function gen() { yield 1; yield 2; }
    foreach (gen() as $v) echo $v;
  33. Question 33

    Generators yield?

    Memory-efficient iterators; yield produces values lazily instead of building huge arrays.

    Example code

    <?php
    declare(strict_types=1);
    function add(int $a, int $b): int { return $a + $b; }
  34. Question 34

    What is declare(strict_types=1)?

    Enforces strict scalar typing per file—arguments and returns won't coerce unexpectedly.

    Example code

    <?php
    // escape output; Content-Security-Policy header
  35. Question 35

    What is XSS in PHP apps?

    Injected markup/script in output; mitigate with escaping, CSP, and avoiding raw echo of user data.

    Example code

    <?php
    // @csrf in Blade / session token in forms
  36. Question 36

    CSRF protection?

    Synchronizer token in forms or SameSite cookies; frameworks provide middleware/helpers.

    Example code

    <?php
    echo password_hash("secret", PASSWORD_DEFAULT);
  37. Question 37

    Password hashing?

    password_hash(PASSWORD_DEFAULT) and password_verify—never store plaintext or use weak hashes.

    Example code

    <?php
    // move_uploaded_file($_FILES["f"]["tmp_name"], $safePath);
  38. Question 38

    File uploads safely?

    Check type/size, store outside webroot or serve via script, randomize filenames, scan if needed.

    Example code

    <?php
    print_r(array_map(fn($x) => $x * 2, [1, 2, 3]));
  39. Question 39

    What is Array functions (PHP context)?

    array_map/filter/reduce, array_merge, array_key_exists—know big-O and copies vs references in large data.

    Example code

    <?php
    $q = new SplQueue();
    $q->enqueue(1);
    echo $q->dequeue();
  40. Question 40

    What is SPL (PHP context)?

    Standard PHP Library: iterators, exceptions, data structures—SplQueue, SplStack for structured collections.

    Example code

    <?php
    // php composer.phar install
  41. Question 41

    What is Phar (PHP context)?

    PHP archives packaging apps; used for tools like Composer phar distribution.

    Example code

    <?php
    // pcov for coverage; xdebug.mode=debug
  42. Question 42

    What is PCOV vs Xdebug (PHP context)?

    Lightweight coverage (PCOV) vs full debugger/profiler (Xdebug)—tradeoffs in CI and local dev.

    Example code

    <?php
    // ./vendor/bin/phpunit
  43. Question 43

    What is PHPUnit basics (PHP context)?

    Unit tests with assertions, data providers, mocks; run in CI on every push.

    Example code

    <?php
    // vendor/bin/phpstan analyse src
  44. Question 44

    What is PHPStan/Psalm (PHP context)?

    Static analysis finds bugs without running code; levels gradually increase strictness.

    Example code

    <?php
    // vendor/bin/rector process src
  45. Question 45

    What is Rector (PHP context)?

    Automated refactoring across PHP versions—helps upgrades 7→8.

    Example code

    <?php
    // dispatch(new SendEmail($u));
  46. Question 46

    What is Laravel queues (PHP context)?

    Defer slow work to workers (Redis/DB); failed_jobs table and retries for resilience.

    Example code

    <?php
    // event(new OrderShipped($order));
  47. Question 47

    What is Laravel events (PHP context)?

    Decouple domains: fire events, listen synchronously or via queue.

    Example code

    <?php
    // Route::get("/users/{user}", fn(User $user) => $user);
  48. Question 48

    What is Route model binding (PHP context)?

    Inject models by ID in routes; implicit or explicit resolution in controllers.

    Example code

    <?php
    // $kernel = new Kernel($env, $debug);
    // $response = $kernel->handle($request);
  49. Question 49

    What is Symfony kernel (PHP context)?

    HttpKernel handles request lifecycle; EventDispatcher hooks many extension points.

    Example code

    <?php
    // $em->persist($entity); $em->flush();
  50. Question 50

    What is Doctrine ORM (PHP context)?

    Data mapper style in Symfony ecosystem; entities, UnitOfWork, DQL vs native SQL tradeoffs.

    Example code

    <?php
    // while (have_posts()) { the_post(); the_title(); }
  51. Question 51

    What is WordPress (PHP context)?

    Loop, hooks (actions/filters), wpdb—different from MVC frameworks; security around plugins/themes matters.

    Example code

    <?php
    // \Drupal::entityTypeManager()->getStorage("node");
  52. Question 52

    What is Drupal (PHP context)?

    Content entities, hooks, Symfony components underneath in modern versions.

    Example code

    <?php
    // $om = \Magento\Framework\App\ObjectManager::getInstance();
  53. Question 53

    What is Magento (PHP context)?

    E-commerce platform; heavy DI XML, plugins (interceptors), performance and caching critical.

    Example code

    <?php
    // opcache.jit=tracing in php.ini
  54. Question 54

    What is OPcache JIT (PHP context)?

    PHP 8 JIT can speed numeric tight loops; impact varies—profile before relying on it.

    Example code

    <?php
    $fiber = new Fiber(fn() => Fiber::suspend("a"));
    $fiber->start();
  55. Question 55

    What is Fibers (PHP context)?

    PHP 8.1 fibers enable cooperative multitasking; async libraries may build atop them.

    Example code

    <?php
    #[\Attribute]
    class Route { public function __construct(public string $path) {} }
  56. Question 56

    What is Attributes (PHP context)?

    PHP 8 metadata on classes/methods replacing docblock annotations in frameworks.

    Example code

    <?php
    readonly class Point { public function __construct(public int $x, public int $y) {} }
  57. Question 57

    What is Readonly class (PHP context)?

    PHP 8.2 readonly classes freeze all properties after construction—immutable DTO pattern.

    Example code

    <?php
    function login(#[\SensitiveParameter] string $pw) {}
    login("x");
  58. Question 58

    What is SensitiveParameter (PHP context)?

    Attribute to redact secrets in stack traces (PHP 8.2).

    Example code

    <?php
    enum S: string { case On = "on"; }
    echo S::On->value;
  59. Question 59

    What is enum backed (PHP context)?

    Backed enums serialize to scalar values; match() exhaustiveness helps switches.

    Example code

    <?php
    echo match (3) { 1 => "a", 2, 3 => "b", default => "z" };
  60. Question 60

    What is match vs switch (PHP context)?

    match is expression, strict compares, no fall-through—safer than switch for many cases.

    Example code

    <?php
    $d = array_map(fn($x) => $x + 1, [1, 2]);
  61. Question 61

    What is Arrow functions fn (PHP context)?

    Short closures capturing outer variables by value automatically (PHP 7.4).

    Example code

    <?php
    $a = [1, ...[2, 3]];
  62. Question 62

    What is Spread in arrays (PHP context)?

    [...$a] copies with integer keys reindexed; beware string keys behavior.

    Example code

    <?php
    echo $user?->profile?->name;
  63. Question 63

    What is Nullsafe operator (PHP context)?

    ?-> chains calls/properties; stops at first null like JS optional chaining.

    Example code

    <?php
    strlen(string: "hi");
  64. Question 64

    What is Named arguments (PHP context)?

    Call functions with parameter names for clarity and skipping defaults (PHP 8).

    Example code

    <?php
    class P { function __construct(public int $x) {} }
  65. Question 65

    What is Constructor promotion (PHP context)?

    Combine property declaration and assignment in constructor parameters (PHP 8).

    Example code

    <?php
    function id(int|string $v): int|string { return $v; }
  66. Question 66

    What is Union types (PHP context)?

    string|int style declarations for parameters and returns.

    Example code

    <?php
    function dumpJson(mixed $d): string { return json_encode($d); }
  67. Question 67

    What is Mixed type (PHP context)?

    Explicit top type when anything is accepted—prefer narrowing inside function.

    Example code

    <?php
    function fail(): never { throw new Exception(); }
  68. Question 68

    What is Never return type (PHP context)?

    Function always exits (throw/exit) or loops forever—helps static analysis.

    Example code

    <?php
    $wm = new WeakMap();
    $o = new stdClass();
    $wm[$o] = 1;
  69. Question 69

    What is WeakMap in PHP (PHP context)?

    Keys are objects; entries disappear when object is GC'd—similar idea to JS WeakMap.

    Example code

    <?php
    $cl = function () { return $this->x; };
    $cl = $cl->bindTo((object)["x"=>1], null);
  70. Question 70

    What is Closure bindTo (PHP context)?

    Change $this and scope of a closure—advanced meta-programming.

    Example code

    <?php
    $r = new ReflectionClass(DateTime::class);
    echo $r->getName();
  71. Question 71

    What is Reflection API (PHP context)?

    Inspect classes at runtime; used in containers, serializers, tests—has a performance cost.

    Example code

    <?php
    // prefer __serialize/__unserialize (PHP 7.4+)
  72. Question 72

    What is Serializable interface (PHP context)?

    Legacy custom serialization; __serialize/__unserialize preferred in modern PHP.

    Example code

    <?php
    class Action { function __invoke() { return 1; } }
    echo (new Action())();
  73. Question 73

    What is __invoke (PHP context)?

    Make an object callable as a function—single-action classes and Laravel invokable controllers.

    Example code

    <?php
    class M { function __get($n) { return 1; } }
    echo (new M())->a;
  74. Question 74

    What is Magic methods (PHP context)?

    __get, __set, __call—convenient but can hide errors and hurt static analysis.

    Example code

    <?php
    class C implements IteratorAggregate { function getIterator(): Traversable { yield 1; } }
  75. Question 75

    What is IteratorAggregate (PHP context)?

    Implement getIterator() to make objects foreach-able cleanly.

    Example code

    <?php
    class Bag implements Countable { function count(): int { return 3; } }
  76. Question 76

    What is Countable interface (PHP context)?

    Implement count() for custom collections.

    Example code

    <?php
    class A implements ArrayAccess { function offsetExists($o): bool { return true; } /* ... */ }
  77. Question 77

    What is ArrayAccess (PHP context)?

    Object behaves like array with offset access—use sparingly for clarity.

    Example code

    <?php
    // $client = new \GuzzleHttp\Client();
    // $client->get("https://api");
  78. Question 78

    What is Guzzle HTTP (PHP context)?

    Popular PSR-7 client; async pools, middleware, retries in ecosystem packages.

    Example code

    <?php
    // $log = new Logger("app"); $log->pushHandler(new StreamHandler("php://stderr"));
  79. Question 79

    What is Monolog (PHP context)?

    Structured logging handlers (stream, syslog, Slack); channels and processors.

    Example code

    <?php
    // echo Carbon::now()->addDays(1);
  80. Question 80

    What is Carbon (PHP context)?

    DateTime wrapper for parsing/formatting/diff common in Laravel.

    Example code

    <?php
    // $redis = new Redis(); $redis->connect("127.0.0.1");
  81. Question 81

    What is Redis in PHP (PHP context)?

    Caching, sessions, queues; connection pooling and serialization format choices matter.

    Example code

    <?php
    // $m = new Memcached(); $m->addServer("127.0.0.1", 11211);
  82. Question 82

    What is Memcached (PHP context)?

    Distributed memory cache; compare persistence and features vs Redis for your workload.

    Example code

    <?php
    // $s3->putObject([...]);
  83. Question 83

    What is S3 uploads (PHP context)?

    Presigned URLs or server-side SDK; never expose long-lived credentials in browser.

    Example code

    <?php
    // Redis INCR + EXPIRE token bucket
  84. Question 84

    What is Rate limiting (PHP context)?

    Throttle by IP/user; token bucket in Redis common for APIs.

    Example code

    <?php
    header("Access-Control-Allow-Origin: https://app.example");
  85. Question 85

    What is CORS in PHP APIs (PHP context)?

    Send Access-Control-* headers from backend; preflight OPTIONS for non-simple requests.

    Example code

    <?php
    $o = json_decode('{"a":1}', true, 512, JSON_THROW_ON_ERROR);
  86. Question 86

    What is JSON (PHP context)?

    json_encode/decode; JSON_THROW_ON_ERROR flag avoids silent failures.

    Example code

    <?php
    $xml = simplexml_load_string("<r/>");
  87. Question 87

    What is XML parsing (PHP context)?

    SimpleXML vs DOMDocument; XXE risks—disable external entities when parsing untrusted XML.

    Example code

    <?php
    preg_match("/^\d+$/", "123", $m);
  88. Question 88

    What is Regular expressions (PHP context)?

    preg_match_all, PCRE modifiers; ReDoS risk with user patterns.

    Example code

    <?php
    $body = stream_get_contents(fopen("php://input", "r"));
  89. Question 89

    What is Streams (PHP context)?

    php://input, fopen wrappers; handle large files without loading all into memory.

    Example code

    <?php
    // cycles collected automatically
  90. Question 90

    What is Garbage collection (PHP context)?

    Cycles collected; long-running workers may need gc_collect_cycles awareness.

    Example code

    <?php
    // ini_set("memory_limit", "256M");
  91. Question 91

    What is Memory limits (PHP context)?

    ini memory_limit; batch processing should chunk to avoid OOM in CLI/cron.

    Example code

    <?php
    // php -d opcache.opt_debug_level=0x10000 script.php
  92. Question 92

    What is Opcodes (PHP context)?

    Understanding vld/opcache output is niche but shows how PHP executes bytecode.

    Example code

    <?php
    // long-lived workers; reset state per request
  93. Question 93

    What is FrankenPHP / RoadRunner (PHP context)?

    Long-lived PHP workers with shared bootstrap—different from classic FPM per-request model.

    Example code

    <?php
    apcu_store("k", 1, 60);
    echo apcu_fetch("k");
  94. Question 94

    What is APCu cache (PHP context)?

    In-process user cache for serialized values—faster than remote cache for local lookups.

    Example code

    <?php
    // php artisan horizon
  95. Question 95

    What is Laravel Horizon (PHP context)?

    Dashboard and metrics for Redis queues; auto-scaling workers in some deployments.

    Example code

    <?php
    // $bus->dispatch(new MyMessage());
  96. Question 96

    What is Symfony Messenger (PHP context)?

    Message bus with transports (sync, AMQP, Redis) for async command handling.

    Example code

    <?php
    // ApiResource attribute on entity
  97. Question 97

    What is API Platform (PHP context)?

    JSON-LD/OpenAPI from entities; rapid API scaffolding on Symfony components.

    Example code

    <?php
    // $user->createToken("device")->plainTextToken
  98. Question 98

    What is Laravel Sanctum (PHP context)?

    SPA/API token auth lightweight alternative to Passport for first-party apps.

    Example code

    <?php
    echo getenv("APP_ENV");
  99. Question 99

    What is Env vars in PHP (PHP context)?

    vlucas/phpdotenv loads .env; never commit secrets; production should use real env injection.

    Example code

    <?php
    // FROM php:8.3-fpm
  100. Question 100

    What is Docker PHP images (PHP context)?

    Official images variants (apache, fpm, cli); match extensions via docker-php-ext-install.

    Example code

    <?php
    // Route::get("/health", fn() => response()->json(["ok" => true]));
  101. Question 101

    What is Health checks (PHP context)?

    Expose /health for load balancers; check DB/Redis connectivity without heavy side effects.

    Example code

    <?php
    // php artisan octane:start
  102. Question 102

    What is Laravel Octane (PHP context)?

    Swoole/RoadRunner-powered app server for Laravel—persistent workers reduce bootstrap cost per request.

    Example code

    // php — add snippet 102