Skip to content
>_ StartupJobList_

Interview questions · Worked answers

PHP interview questions and worked answers

Make runtime boundaries explicit: validate incoming values, preserve useful error distinctions, own resource cleanup, and measure the actual PHP worker before tuning. The examples separate language behavior from framework or server behavior.

For: PHP developers maintaining web applications and command-line services

Guide scope and versions

Targets PHP 8.3 and 8.4-era language features. Strict scalar typing is caller-file-specific, Fibers require an event-loop or scheduler for I/O concurrency, and OPcache/JIT settings depend on deployment configuration.

Question 1 of 12

What does `strict_types=1` actually make strict?

It affects scalar argument coercion for calls made from that file. Return-value coercion follows the strictness of the file where the function is defined. It does not turn PHP into a runtime schema validator, and a call from a coercive file can still coerce arguments to a function declared in a strict file.

A library function expects an integer amount. If a caller in a file without strict mode passes a numeric string, PHP may coerce it even when the function was declared in a strict file. For a return declaration, strictness follows the function's defining file. This rule is distinct from validating request JSON or database data, which still needs explicit boundary validation.

Type declarations improve contracts and static analysis, but they do not validate nested array shape or external data by themselves. Parse untrusted input into a typed value object only after checking its structure and domain constraints.

PHP · Worked example
<?php
declare(strict_types=1);
function charge(int $cents): int { return $cents; }
assert(charge(1200) === 1200);
$rejected = false;
try { charge('1200'); }
catch (TypeError $error) { $rejected = $error instanceof TypeError; }
assert($rejected);
echo "strict caller rejected string\n";

The strict declaration affects calls made from this file. A function being declared in a strict file does not force every caller file to be strict.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: How do you validate decoded JSON?

Check whether decoding succeeded, verify the expected object/array shape, then validate each field's type and domain rule. Convert the checked data into a domain type so later code does not repeatedly guess what it contains.

Read the source: PHP type declarations: strict typing · PHP JSON decoding

↑ Back to questions

Question 2 of 12

When should an API use a union type or a value object?

Use a union when a small number of valid alternatives are part of the contract. Use a value object when the alternatives carry domain rules, validation, or behavior that callers would otherwise duplicate.

A lookup returning User|null clearly represents a missing user. A function returning User|false|string|array forces every caller to infer what each shape means. A LookupResult object can name found and missing states and keep invalid combinations out of the API.

Union and intersection declarations describe accepted PHP types, not all semantic constraints. int does not prove a value is positive, and string does not prove it is a valid email. Validate those invariants at construction or input boundaries.

PHP · Worked example
<?php
declare(strict_types=1);
final class Money {
    public function __construct(public readonly int $cents, public readonly string $currency) {
        if ($cents < 0 || !preg_match('/^[A-Z]{3}$/', $currency)) throw new InvalidArgumentException('Invalid money value');
    }
}
$value = new Money(1250, 'EUR');
assert($value->cents === 1250 && $value->currency === 'EUR');
$rejected = false;
try { new Money(-1, 'EUR'); }
catch (InvalidArgumentException $error) { $rejected = $error->getMessage() === 'Invalid money value'; }
assert($rejected);

The constructor guards domain constraints that native scalar declarations cannot express. A real money type may need currency-specific scale and arithmetic rules beyond this small sketch.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: When is an array return still reasonable?

For a local internal helper with a small, stable, obvious shape. Across package or public service boundaries, named types and documented fields make invalid states harder to create and easier to evolve.

Read the source: PHP type declarations · PHP property declarations

↑ Back to questions

Question 3 of 12

How do exceptions and `finally` affect cleanup?

An uncaught throwable bubbles up the call stack, while each encountered finally runs during unwinding. Catch only where the code can recover, translate, or add useful context; catching broadly and continuing can turn a failed operation into corrupted success.

A service reserves inventory and then charges a payment provider. If the charge fails, cleanup or compensation must be explicit. A finally block guarantees its cleanup code is entered during normal unwinding, but cleanup can itself throw and change the exception the caller observes.

PHP's Throwable covers both Exception and engine Error types. Catching Throwable at a process boundary can be useful for logging and controlled shutdown, but an inner business method should not silently treat programming errors like expected validation failures.

PHP · Worked example
<?php
declare(strict_types=1);
function parse_stream($handle): array {
    $line = fgets($handle);
    if ($line === false) throw new RuntimeException('Empty input');
    return json_decode($line, true, flags: JSON_THROW_ON_ERROR);
}
$handle = fopen('php://memory', 'w+');
fwrite($handle, "{\"id\":7}\n"); rewind($handle);
try { $parsed = parse_stream($handle); }
finally { fclose($handle); }
assert($parsed['id'] === 7 && !is_resource($handle));
$broken = fopen('php://memory', 'w+'); fwrite($broken, '{'); rewind($broken);
try { parse_stream($broken); }
catch (JsonException $error) { assert($error instanceof JsonException); }
finally { fclose($broken); }
assert(!is_resource($broken));

The handle is closed whether parsing returns or throws. In production, a resource-owning object or a dedicated abstraction can make ownership clearer when the handle must cross method boundaries.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: Where should an exception become an HTTP response?

At the request boundary that knows the public status and safe message. Preserve the cause for internal diagnostics, but do not expose database, filesystem, or provider details to the client.

Read the source: PHP exceptions · PHP finally behavior

↑ Back to questions

Question 4 of 12

When can a generator reduce memory use?

A generator yields values on demand, which can avoid building a complete result array. It only reduces memory if the producer and every downstream step avoid retaining the whole dataset.

An import reads a large newline-delimited file. A generator can parse one record at a time and hand it to a bounded batch writer. Calling iterator_to_array() or accumulating every record in a result array defeats the streaming design.

A generator pauses at yield and resumes when the consumer requests another value. Give the resource a clear owner. When the caller owns the file or cursor, keep iteration inside the caller's try/finally so an early break still closes it. If a generator opens a resource internally, it has no public close() method; releasing the last generator reference triggers destruction, so cleanup timing depends on ownership and references.

PHP · Worked example
<?php
declare(strict_types=1);
function records($handle): Generator {
    while (($line = fgets($handle)) !== false) yield json_decode($line, true, flags: JSON_THROW_ON_ERROR);
}
$handle = fopen('php://memory', 'w+');
fwrite($handle, "{\"id\":1}\n{\"broken\":\"\n"); rewind($handle);
try {
    foreach (records($handle) as $record) { assert($record['id'] === 1); break; }
} finally { fclose($handle); }
assert(!is_resource($handle));
$broken = fopen('php://memory', 'w+'); fwrite($broken, '{'); rewind($broken);
try { foreach (records($broken) as $record) {} }
catch (JsonException $error) { assert($error instanceof JsonException); }
finally { fclose($broken); }
assert(!is_resource($broken));

The caller owns the stream, so its finally closes the resource even when iteration stops early or JSON decoding throws. The in-memory stream keeps the example self-contained; replace it with an opened file in an importer.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: What if the generator opens the file internally and the consumer stops early?

Prefer an API where the caller opens and owns the file, then closes it in finally around the loop. If the generator owns the resource, cleanup runs when it completes or is destroyed; releasing the last reference can trigger destruction, but break alone does not give a deterministic close while that generator remains referenced. For cursors, use the driver's explicit close API.

Read the source: PHP generators · Generator syntax and iteration · Generator class reference

↑ Back to questions

Question 5 of 12

Do PHP Fibers make blocking I/O asynchronous by themselves?

No. A Fiber provides a suspendable call stack, but an event loop or library must arrange when suspended work resumes. Calling a blocking API still blocks the current thread unless that API cooperates with the scheduler.

A legacy function performs nested HTTP work. A Fiber can suspend from inside a call stack without every function changing its return type, but some scheduler-aware client must suspend while waiting and resume when the socket is ready. The core Fiber primitive does not transparently make file_get_contents() nonblocking.

Fibers are a control-flow primitive. The application still needs policies for deadlines, cancellation, error propagation, and bounded concurrency. Keep synchronous request/response PHP separate from a long-running worker's lifecycle assumptions.

PHP · Worked example
<?php
declare(strict_types=1);
$fiber = new Fiber(function (): string { return Fiber::suspend('waiting'); });
$yielded = $fiber->start();
assert($yielded === 'waiting');
$fiber->resume('resumed');
assert($fiber->isTerminated() && $fiber->getReturn() === 'resumed');

The example shows suspension and resumption only. It does not perform I/O or provide parallel execution; a scheduler must decide when to resume a suspended operation.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: When would a Fiber-based design be useful?

When a compatible event loop or library already coordinates many I/O waits and the synchronous-looking call stack improves integration. Compare it with simpler synchronous workers or explicit promises using measured workload and operational complexity.

Read the source: PHP Fibers overview · PHP Fiber class

↑ Back to questions

Question 6 of 12

Who owns a database transaction or file handle?

The function that opens or begins a resource should usually own its close, rollback, or commit path. Make ownership explicit when returning a resource-backed iterator or handing a transaction to another layer.

A repository method begins a transaction, writes two related rows, and commits. If the second write fails, it rolls back before returning. If a method receives an existing transaction, it should not commit a transaction it does not own.

A finally block is useful for deterministic local cleanup. Resource APIs differ in their semantics, and a failed rollback may itself matter; preserve the original failure and report cleanup failure without silently claiming the operation was rolled back.

PHP · Worked example
<?php
declare(strict_types=1);
$pdo = new PDO(getenv('BACKEND_TEST_DSN'), getenv('BACKEND_TEST_USER'), getenv('BACKEND_TEST_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$serverVersion = (int) $pdo->query('SHOW server_version_num')->fetchColumn();
assert($serverVersion >= 160000 && $serverVersion < 170000);
$pdo->exec('CREATE TEMP TABLE proof_orders (id integer PRIMARY KEY, state text NOT NULL)');
$pdo->beginTransaction();
try {
    $pdo->exec("INSERT INTO proof_orders VALUES (1, 'created')");
    throw new RuntimeException('stock reservation failed');
    $pdo->commit();
} catch (Throwable $error) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    assert($error->getMessage() === 'stock reservation failed');
}
assert((int) $pdo->query('SELECT count(*) FROM proof_orders')->fetchColumn() === 0);

This function owns the transaction. If a caller may already have an open transaction, use a separate API contract rather than nesting this ownership pattern blindly. A commit/network failure can leave the final database outcome uncertain.

Executed with PHP 8.4.27 and PDO against a disposable synthetic PostgreSQL 16 fixture; assertions passed.

Follow-up: How should a caller retry after a connection error during commit?

Treat the outcome as potentially unknown. Use an idempotency key or query the durable operation record before repeating a non-idempotent command.

Read the source: PDO transactions · PDO inTransaction

↑ Back to questions

Question 7 of 12

What does OPcache improve, and when can it serve stale code?

OPcache stores precompiled script bytecode in shared memory so PHP does not need to parse and compile each script on every request. Freshness depends on configuration and deployment behavior; cache validation and invalidation must match how code is released.

A web application sees high CPU in repeated script compilation. Confirm OPcache is enabled for the actual SAPI, then inspect status and hit/miss data. CLI configuration can differ from PHP-FPM, so a CLI check does not prove the web workers use the same settings.

With timestamp validation disabled, changed files may not be noticed until invalidation or worker restart. PHP 8.4 changed the default JIT setting to disabled; enabling JIT is a separate choice and should follow a profile, not a blanket performance assumption.

PHP · Worked example
<?php
declare(strict_types=1);
$status = function_exists('opcache_get_status') ? opcache_get_status(false) : false;
$enabled = is_array($status) ? ($status['opcache_enabled'] ?? false) : false;
assert(is_bool($enabled));
echo $enabled ? "opcache-enabled\n" : "opcache-disabled\n";

The CLI run reported opcache-disabled. Inspect status from the same SAPI and worker configuration used by the application; CLI status does not establish FPM status.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: Should a production release call opcache_reset()?

Choose a deployment-owned invalidation or worker-restart strategy appropriate to the hosting model. A global reset can affect unrelated applications sharing the cache, so understand the SAPI/cache scope first.

Read the source: OPcache overview · OPcache runtime configuration

↑ Back to questions

Question 8 of 12

How do you test a PHP boundary and diagnose a slow request?

Test input validation, observable outcomes, and failure paths at the boundary, then profile before tuning. A mock can isolate a unit but cannot prove database transaction, extension, SAPI, or deployment behavior.

For a JSON endpoint, test malformed JSON, missing fields, invalid domain values, successful output, and a dependency failure. Keep unit tests fast; add integration coverage for behavior that belongs to the database or PHP runtime itself.

For latency, split request time into application CPU, database, network, and queueing evidence. OPcache reduces repeated compilation; it does not make a slow query or remote call fast. JIT changes should be measured against the supported PHP version and actual workload.

PHP · Worked example
<?php
declare(strict_types=1);
function decode_payload(string $body): array {
    $payload = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
    if (!is_array($payload) || !is_string($payload['email'] ?? null)) throw new InvalidArgumentException('Expected an email string');
    return $payload;
}
assert(decode_payload('{"email":"a@example.test"}')['email'] === 'a@example.test');
foreach (["{", '{"email":7}', '[]'] as $invalid) {
    try { decode_payload($invalid); }
    catch (JsonException|InvalidArgumentException $error) { continue; }
    throw new AssertionError('invalid payload accepted');
}

This separates JSON syntax errors from the expected object shape and field type. A production endpoint should also validate the email/domain rule and map exceptions to a safe response.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: What would you measure before enabling JIT?

Profile CPU time in the same PHP version and SAPI under representative traffic, check whether PHP execution is a material bottleneck, and compare repeatable latency/throughput results with and without the setting.

Read the source: PHP JSON decoding · OPcache and JIT settings

↑ Back to questions

Question 9 of 12

How do array copies, object handles and references differ?

Array assignment normally gives value semantics, while assigning an object copies its object identifier. An explicit & reference aliases a variable container. These three operations have different mutation consequences; none should be described simply as “everything is passed by reference.”

PHP can share underlying array storage until a write requires separation. This copy-on-write implementation avoids an eager full copy, but the observable assignment semantics remain value semantics for ordinary values. Objects inside an array are still objects: copying the outer array does not recursively clone them.

After a by-reference foreach, the loop variable can remain an alias to the last element. A later assignment to that variable can unexpectedly overwrite the array element. Unset the reference variable after the loop, and prefer a non-reference loop when mutation through an alias is unnecessary.

PHP · Worked example
$a = [1, 2];
$b = $a;
$b[0] = 9;
assert($a[0] === 1);

$original = (object) ["name" => "Ada"];
$other = $original;
$other->name = "Lin";
assert($original->name === "Lin");

$alias =& $a;
$alias[0] = 7;
assert($a[0] === 7);
unset($alias);

The array write leaves the first array unchanged. The object property write is visible through both object identifiers. The explicit reference makes the final array write visible through both variable names; unsetting the alias removes that variable without removing the original array.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: Does passing an object to a function let it replace the caller’s variable?

Ordinary parameter passing lets the function mutate the referenced object, but assigning a different object to its local parameter does not replace the caller’s variable. That requires an explicit reference parameter or returning the replacement.

Read the source: PHP references · PHP objects and references

↑ Back to questions

Question 10 of 12

What do prepared statements protect, and what must still be allowlisted?

Bind untrusted values as parameters instead of interpolating them into SQL. Parameters stand for complete data values, not table names, column identifiers, sort directions or arbitrary SQL syntax. Choose dynamic identifiers from a fixed server-owned allowlist.

A search endpoint often needs both a user-supplied filter and a selected sort order. Bind the filter value, then map the sort choice to a known SQL fragment. Escaping a string and treating it as SQL structure is a different operation and is easy to get wrong.

Native versus emulated preparation depends on the PDO driver and configuration. Check the driver’s behavior and error mode. Preparation does not supply authorization: a safely bound customer ID can still expose another tenant’s rows unless the query includes the authenticated tenant boundary.

PHP · Worked example
<?php
declare(strict_types=1);
$pdo = new PDO(getenv('BACKEND_TEST_DSN'), getenv('BACKEND_TEST_USER'), getenv('BACKEND_TEST_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$serverVersion = (int) $pdo->query('SHOW server_version_num')->fetchColumn();
assert($serverVersion >= 160000 && $serverVersion < 170000);
$pdo->exec('CREATE TEMP TABLE proof_jobs (id integer, tenant_id integer, title text, created_at integer)');
$pdo->exec("INSERT INTO proof_jobs VALUES (1, 7, 'Backend', 20), (2, 8, 'Backend', 30)");
$tenant = 7; $title = 'Backend'; $sort = 'newest';
$sorts = ['newest' => 'created_at DESC, id DESC', 'oldest' => 'created_at ASC, id ASC'];
$order = $sorts[$sort] ?? throw new InvalidArgumentException('Unknown sort');
$stmt = $pdo->prepare('SELECT id, title FROM proof_jobs WHERE tenant_id = :tenant AND title = :title ORDER BY ' . $order);
$stmt->execute(['tenant' => $tenant, 'title' => $title]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
assert(count($rows) === 1 && (int) $rows[0]['id'] === 1 && $rows[0]['title'] === 'Backend');

Only the allowlisted order expression becomes SQL syntax. Both tenant and title are data parameters, and the tenant comes from authenticated server context rather than an untrusted field. This query ran with PDO against a disposable PostgreSQL 16 database and returned only the matching tenant row.

Executed with PHP 8.4.27 and PDO against a disposable synthetic PostgreSQL 16 fixture; assertions passed.

Follow-up: What changes for a user-selected list of IDs?

Validate and bound the list, generate one placeholder per value and bind each value. Handle an empty list explicitly. Do not concatenate untrusted IDs or allow an unbounded input to create an enormous query.

Read the source: PDO prepared statements · PDO prepare parameter limits

↑ Back to questions

Question 11 of 12

Why can two requests from one user block each other?

A session handler may lock the session while a request holds it open. With the common file handler, a slow request can block another request using the same session. Read and update the required state, then close the session before unrelated slow work when that matches the application’s consistency needs.

Session data is server-side state keyed by a client-held identifier. A long export and a dashboard request can appear to run serially because they share a session lock, even when workers are otherwise available. Handler-specific behavior matters; changing storage does not automatically preserve the same locking guarantees.

Close the session only after required writes. Changes made to the in-memory session array after closing are not automatically persisted. Authentication also needs safe cookie attributes, session-ID regeneration at privilege changes and a policy for concurrent old-session requests. Releasing a lock does not solve fixation, CSRF or authorization.

PHP · Worked example
<?php
declare(strict_types=1);
session_id('backend-proof-session');
session_start();
$_SESSION['user_id'] = 19;
session_write_close();
session_id('backend-proof-session');
session_start();
$userId = $_SESSION['user_id'] ?? null;
assert($userId === 19);
session_write_close();
assert(session_status() === PHP_SESSION_NONE);

The request snapshots the identity it needs and releases the session before slow work. The actual data operation must still enforce authorization. This is a lifecycle sketch, not a complete login flow or session configuration.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: Does releasing the session lock make concurrent updates safe?

No. If two requests read then update related state, define an atomic store operation or a transaction at the authoritative data layer. A session lock and a business transaction protect different boundaries.

Read the source: PHP session_write_close · PHP session security

↑ Back to questions

Question 12 of 12

What changes when PHP runs in a long-lived application worker?

In a traditional request lifecycle, application request state is rebuilt for each request even though a PHP-FPM process can serve many requests. A long-lived application worker may retain application objects between requests. Request-specific identity, transactions and mutable caches then need explicit lifecycle ownership.

Distinguish process lifetime, opcode-cache lifetime, connection lifetime and request lifetime. A PHP-FPM worker being reused does not mean ordinary local variables from the previous request are a supported cross-request store. Conversely, a framework that boots an application once inside a worker can retain its service objects.

A singleton carrying a tenant ID is especially dangerous in a persistent application: the next request might inherit the previous identity. Pass request context explicitly, reset scoped services at the correct boundary and test alternating users in the same worker. Cleanup in finally must run on exceptions; process termination and resource limits remain separate cases.

PHP · Worked example
<?php
declare(strict_types=1);
final class Request { public function __construct(public int $userId) {} }
final class Response { public function __construct(public int $userId) {} }
final class Service {
    private ?int $requestUser = null;
    public function respond(int $userId): Response { $this->requestUser = $userId; return new Response($this->requestUser); }
    public function clearRequestState(): void { $this->requestUser = null; }
    public function currentUser(): ?int { return $this->requestUser; }
}
function authenticate(Request $request): int { return $request->userId; }
function handleRequest(Request $request, Service $service): Response {
    $context = authenticate($request);
    try { return $service->respond($context); }
    finally { $service->clearRequestState(); }
}
$service = new Service();
assert(handleRequest(new Request(1), $service)->userId === 1 && $service->currentUser() === null);
assert(handleRequest(new Request(2), $service)->userId === 2 && $service->currentUser() === null);

The skeleton makes cleanup part of the request contract and names the cross-request test. The classes and authentication function are application-owned placeholders. Clearing state is a safeguard, not a reason to store identity globally in the first place.

Executed with PHP 8.4.27 in an isolated CLI process; assertions passed.

Follow-up: Which test exposes a request-state leak?

Run an authorized request for tenant A, then a different tenant B and an unauthenticated request through the same worker/service instance, including an exception path. Assert that each result and query uses only its own context.

Read the source: PHP persistent database connections · PHP static variables

↑ Back to questions

Salary context

Advertised salaries for these skills

These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.

PHP posts

25 posts · 25 usable advertised salary amounts

2024-07-08 to 2026-11-02

Not enough usable observations for an aggregate salary: at least 30 are needed. Individual source offers can still be useful.

Explore PHP salaries → Browse matching job posts →
Currency and calculation basis

Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged PHP, rather than every job in the broader technology family.

↑ Back to questions

Keep exploring