Pick a topic — languages & databases — 100+ questions and answers in the center column.
PHP
Server-side scripting, Laravel-style topics, runtime.
102 questions
Question 1
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";Question 2
== compares with type juggling; === compares type and value. Prefer === to avoid surprising coercion.
Example code
<?php
var_dump(0 == "0", 0 === "0");Question 3
$_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";Question 4
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";Question 5
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");Question 6
Dependency manager for PHP: composer.json declares packages; vendor/ and autoload.php wire class loading.
Example code
<?php
// composer require vendor/autoload.phpQuestion 7
Avoids class name collisions; use statement imports symbols. PSR-4 ties namespaces to directory paths.
Example code
<?php
namespace App\Models;
class User {}Question 8
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; }Question 9
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; }Question 10
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; }Question 11
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; }Question 12
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]);Question 13
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]);Question 14
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");Question 15
session_start() ties a cookie (PHPSESSID) to server-side storage; $_SESSION persists per user across requests.
Example code
<?php
session_start();
$_SESSION["uid"] = 1;Question 16
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"]);Question 17
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");Question 18
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);Question 19
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 productionQuestion 20
FastCGI Process Manager runs PHP workers behind nginx/Apache; pools, workers, and timeouts tune concurrency.
Example code
<?php
// php-fpm pool pm.max_children tuningQuestion 21
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"));Question 22
Active-record style models; relationships (hasMany, belongsTo), migrations, and query builder fluent API.
Example code
<?php
// User::with("posts")->get();Question 23
Compiled to plain PHP; @if, @foreach, layouts/components—escape with {{ }} by default.
Example code
<?php
// @foreach($items as $i) {{ $i->name }} @endforeachQuestion 24
HTTP pipeline layers that inspect/modify request/response (auth, logging) before the controller.
Example code
<?php
// $stack->push(new AuthMiddleware());Question 25
Component-based framework and full stack; HttpFoundation, DependencyInjection, used standalone or in Laravel pieces.
Example code
<?php
// $container->bind(I::class, Impl::class);Question 26
Constructor injection of services/interfaces; containers (Laravel/Symfony) resolve concrete implementations.
Example code
<?php
use Psr\Http\Message\ServerRequestInterface;Question 27
HTTP message interfaces (Request/Response) enabling interoperable middleware and clients.
Example code
<?php
// composer dump-autoload -oQuestion 28
Autoloading standard mapping namespaces to directory structures—Composer's default.
Example code
<?php
try { throw new Exception("x"); } catch (Exception $e) { echo $e->getMessage(); }Question 29
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; }Question 30
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";Question 31
Returns left if set and not null, else right—cleaner than isset ternary chains.
Example code
<?php
usort($a, fn($x, $y) => $x <=> $y);Question 32
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;Question 33
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; }Question 34
Enforces strict scalar typing per file—arguments and returns won't coerce unexpectedly.
Example code
<?php
// escape output; Content-Security-Policy headerQuestion 35
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 formsQuestion 36
Synchronizer token in forms or SameSite cookies; frameworks provide middleware/helpers.
Example code
<?php
echo password_hash("secret", PASSWORD_DEFAULT);Question 37
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);Question 38
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]));Question 39
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();Question 40
Standard PHP Library: iterators, exceptions, data structures—SplQueue, SplStack for structured collections.
Example code
<?php
// php composer.phar installQuestion 41
PHP archives packaging apps; used for tools like Composer phar distribution.
Example code
<?php
// pcov for coverage; xdebug.mode=debugQuestion 42
Lightweight coverage (PCOV) vs full debugger/profiler (Xdebug)—tradeoffs in CI and local dev.
Example code
<?php
// ./vendor/bin/phpunitQuestion 43
Unit tests with assertions, data providers, mocks; run in CI on every push.
Example code
<?php
// vendor/bin/phpstan analyse srcQuestion 44
Static analysis finds bugs without running code; levels gradually increase strictness.
Example code
<?php
// vendor/bin/rector process srcQuestion 45
Automated refactoring across PHP versions—helps upgrades 7→8.
Example code
<?php
// dispatch(new SendEmail($u));Question 46
Defer slow work to workers (Redis/DB); failed_jobs table and retries for resilience.
Example code
<?php
// event(new OrderShipped($order));Question 47
Decouple domains: fire events, listen synchronously or via queue.
Example code
<?php
// Route::get("/users/{user}", fn(User $user) => $user);Question 48
Inject models by ID in routes; implicit or explicit resolution in controllers.
Example code
<?php
// $kernel = new Kernel($env, $debug);
// $response = $kernel->handle($request);Question 49
HttpKernel handles request lifecycle; EventDispatcher hooks many extension points.
Example code
<?php
// $em->persist($entity); $em->flush();Question 50
Data mapper style in Symfony ecosystem; entities, UnitOfWork, DQL vs native SQL tradeoffs.
Example code
<?php
// while (have_posts()) { the_post(); the_title(); }Question 51
Loop, hooks (actions/filters), wpdb—different from MVC frameworks; security around plugins/themes matters.
Example code
<?php
// \Drupal::entityTypeManager()->getStorage("node");Question 52
Content entities, hooks, Symfony components underneath in modern versions.
Example code
<?php
// $om = \Magento\Framework\App\ObjectManager::getInstance();Question 53
E-commerce platform; heavy DI XML, plugins (interceptors), performance and caching critical.
Example code
<?php
// opcache.jit=tracing in php.iniQuestion 54
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();Question 55
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) {} }Question 56
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) {} }Question 57
PHP 8.2 readonly classes freeze all properties after construction—immutable DTO pattern.
Example code
<?php
function login(#[\SensitiveParameter] string $pw) {}
login("x");Question 58
Attribute to redact secrets in stack traces (PHP 8.2).
Example code
<?php
enum S: string { case On = "on"; }
echo S::On->value;Question 59
Backed enums serialize to scalar values; match() exhaustiveness helps switches.
Example code
<?php
echo match (3) { 1 => "a", 2, 3 => "b", default => "z" };Question 60
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]);Question 61
Short closures capturing outer variables by value automatically (PHP 7.4).
Example code
<?php
$a = [1, ...[2, 3]];Question 62
[...$a] copies with integer keys reindexed; beware string keys behavior.
Example code
<?php
echo $user?->profile?->name;Question 63
?-> chains calls/properties; stops at first null like JS optional chaining.
Example code
<?php
strlen(string: "hi");Question 64
Call functions with parameter names for clarity and skipping defaults (PHP 8).
Example code
<?php
class P { function __construct(public int $x) {} }Question 65
Combine property declaration and assignment in constructor parameters (PHP 8).
Example code
<?php
function id(int|string $v): int|string { return $v; }Question 66
string|int style declarations for parameters and returns.
Example code
<?php
function dumpJson(mixed $d): string { return json_encode($d); }Question 67
Explicit top type when anything is accepted—prefer narrowing inside function.
Example code
<?php
function fail(): never { throw new Exception(); }Question 68
Function always exits (throw/exit) or loops forever—helps static analysis.
Example code
<?php
$wm = new WeakMap();
$o = new stdClass();
$wm[$o] = 1;Question 69
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);Question 70
Change $this and scope of a closure—advanced meta-programming.
Example code
<?php
$r = new ReflectionClass(DateTime::class);
echo $r->getName();Question 71
Inspect classes at runtime; used in containers, serializers, tests—has a performance cost.
Example code
<?php
// prefer __serialize/__unserialize (PHP 7.4+)Question 72
Legacy custom serialization; __serialize/__unserialize preferred in modern PHP.
Example code
<?php
class Action { function __invoke() { return 1; } }
echo (new Action())();Question 73
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;Question 74
__get, __set, __call—convenient but can hide errors and hurt static analysis.
Example code
<?php
class C implements IteratorAggregate { function getIterator(): Traversable { yield 1; } }Question 75
Implement getIterator() to make objects foreach-able cleanly.
Example code
<?php
class Bag implements Countable { function count(): int { return 3; } }Question 76
Implement count() for custom collections.
Example code
<?php
class A implements ArrayAccess { function offsetExists($o): bool { return true; } /* ... */ }Question 77
Object behaves like array with offset access—use sparingly for clarity.
Example code
<?php
// $client = new \GuzzleHttp\Client();
// $client->get("https://api");Question 78
Popular PSR-7 client; async pools, middleware, retries in ecosystem packages.
Example code
<?php
// $log = new Logger("app"); $log->pushHandler(new StreamHandler("php://stderr"));Question 79
Structured logging handlers (stream, syslog, Slack); channels and processors.
Example code
<?php
// echo Carbon::now()->addDays(1);Question 80
DateTime wrapper for parsing/formatting/diff common in Laravel.
Example code
<?php
// $redis = new Redis(); $redis->connect("127.0.0.1");Question 81
Caching, sessions, queues; connection pooling and serialization format choices matter.
Example code
<?php
// $m = new Memcached(); $m->addServer("127.0.0.1", 11211);Question 82
Distributed memory cache; compare persistence and features vs Redis for your workload.
Example code
<?php
// $s3->putObject([...]);Question 83
Presigned URLs or server-side SDK; never expose long-lived credentials in browser.
Example code
<?php
// Redis INCR + EXPIRE token bucketQuestion 84
Throttle by IP/user; token bucket in Redis common for APIs.
Example code
<?php
header("Access-Control-Allow-Origin: https://app.example");Question 85
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);Question 86
json_encode/decode; JSON_THROW_ON_ERROR flag avoids silent failures.
Example code
<?php
$xml = simplexml_load_string("<r/>");Question 87
SimpleXML vs DOMDocument; XXE risks—disable external entities when parsing untrusted XML.
Example code
<?php
preg_match("/^\d+$/", "123", $m);Question 88
preg_match_all, PCRE modifiers; ReDoS risk with user patterns.
Example code
<?php
$body = stream_get_contents(fopen("php://input", "r"));Question 89
php://input, fopen wrappers; handle large files without loading all into memory.
Example code
<?php
// cycles collected automaticallyQuestion 90
Cycles collected; long-running workers may need gc_collect_cycles awareness.
Example code
<?php
// ini_set("memory_limit", "256M");Question 91
ini memory_limit; batch processing should chunk to avoid OOM in CLI/cron.
Example code
<?php
// php -d opcache.opt_debug_level=0x10000 script.phpQuestion 92
Understanding vld/opcache output is niche but shows how PHP executes bytecode.
Example code
<?php
// long-lived workers; reset state per requestQuestion 93
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");Question 94
In-process user cache for serialized values—faster than remote cache for local lookups.
Example code
<?php
// php artisan horizonQuestion 95
Dashboard and metrics for Redis queues; auto-scaling workers in some deployments.
Example code
<?php
// $bus->dispatch(new MyMessage());Question 96
Message bus with transports (sync, AMQP, Redis) for async command handling.
Example code
<?php
// ApiResource attribute on entityQuestion 97
JSON-LD/OpenAPI from entities; rapid API scaffolding on Symfony components.
Example code
<?php
// $user->createToken("device")->plainTextTokenQuestion 98
SPA/API token auth lightweight alternative to Passport for first-party apps.
Example code
<?php
echo getenv("APP_ENV");Question 99
vlucas/phpdotenv loads .env; never commit secrets; production should use real env injection.
Example code
<?php
// FROM php:8.3-fpmQuestion 100
Official images variants (apache, fpm, cli); match extensions via docker-php-ext-install.
Example code
<?php
// Route::get("/health", fn() => response()->json(["ok" => true]));Question 101
Expose /health for load balancers; check DB/Redis connectivity without heavy side effects.
Example code
<?php
// php artisan octane:startQuestion 102
Swoole/RoadRunner-powered app server for Laravel—persistent workers reduce bootstrap cost per request.
Example code
// php — add snippet 102