Back to interview questions

100+ PHP Interview Questions and Answers

100+ PHP Interview Questions and Answers

Explore 120 PHP interview questions and answers on types, arrays, OOP, PDO, security, Composer, testing, runtime behavior and production engineering.

Explore 120 PHP interview questions and answers on types, arrays, OOP, PDO, security, Composer, testing, runtime behavior and production engineering.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

PHP interviews should reveal whether candidates can explain what their code does at a request, data and runtime boundary. Recruiters can ask a developer to distinguish a valid zero from failure, review a parameterized query, or trace what happens when a worker retries a payment after a timeout. These exercises reveal language understanding and production judgment more clearly than a list of syntax definitions alone.

This guide to 100+ PHP Interview Questions and Answers contains 120 questions across beginner, intermediate and experienced levels. It covers modern PHP language behavior, types, arrays, objects, secure request handling, PDO, Composer, testing and production operations. Select questions for the role: maintaining a small PHP application and operating a long-lived service require overlapping foundations but different depth.

How can recruiters address potential AI cheating, deepfakes, impersonation and unauthorized assistance during PHP interviews?

Ask candidates to predict a short example’s output, explain the relevant type or lifecycle rule, and then revise the solution when the input or deployment assumption changes. State permitted tools consistently and ask follow-ups about error paths, security boundaries and tests. A candidate who understands the code should be able to explain both its intended behavior and a condition under which it fails.

Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation and unauthorized real-time assistance during PHP interviews. Combine those signals with the candidate’s reasoning and work, and review concerns in context rather than treating a signal as proof of misconduct.

PHP Interview Questions

The guide uses modern PHP 8.x. Standalone code examples target PHP 8.2 or later unless a newer requirement or extension is explicitly labeled; property hooks require PHP 8.4 and the pipe example requires PHP 8.5. Choose a supported deployment version and verify the extensions and configuration relevant to the role.

PHP Interview Questions for Beginners

Start with request execution, value types, functions, objects and safe boundaries. These questions test whether a candidate can reason about ordinary PHP code without relying on accidental coercion or hidden global state.

  1. What is PHP, and where does it run in a web application?

  2. How does a typical PHP-FPM request reach application code?

  3. Why do PHP-only files usually omit the closing PHP tag?

  4. How do variables and constants differ in PHP?

  5. Which basic value types should a PHP developer understand?

  6. How do loose equality and strict equality differ?

  7. Why should money usually not be calculated with ordinary floating-point values?

  8. How do single-quoted and double-quoted strings differ?

  9. What is unusual about PHP arrays compared with arrays in some other languages?

  10. How do isset(), array_key_exists() and empty() answer different questions?

  11. What does the null coalescing operator do?

  12. How do foreach loops behave when iterating by reference?

  13. What is the scope of a variable inside a PHP function?

  14. How do passing by value and passing by reference differ?

  15. What do parameter and return type declarations provide?

  16. What does declare(strict_types=1) change?

  17. How do nullable and union types differ?

  18. How do void and never return types differ?

  19. How do named arguments change an API's compatibility concerns?

  20. What are variadic parameters useful for?

  21. How do closures capture variables from their surrounding scope?

  22. How are arrow functions different from ordinary anonymous functions?

  23. What does match improve compared with switch?

  24. What does the nullsafe operator protect against?

  25. How do include and require differ?

  26. What problem do namespaces solve?

  27. How does Composer help a PHP application?

  28. How does PSR-4 autoloading connect a class name to a file?

  29. What is the difference between a class and an object?

  30. How do public, protected and private visibility differ?

  31. When should an interface be preferred to an abstract class?

  32. What are traits, and what problems can they introduce?

  33. What does constructor property promotion do?

  34. What does readonly mean for a property or class?

  35. When are enums better than loose strings?

  36. How do exceptions and PHP Error objects relate?

  37. What is finally useful for?

  38. How should a PHP endpoint read and validate incoming data?

  39. Why must output escaping match its destination context?

  40. How should application errors be exposed in development and production?

PHP Interview Questions for Intermediate

Examine array semantics, data conversion, object contracts, persistence, authentication and tests. Candidates should explain how the chosen PHP API behaves and what remains the application’s responsibility.

  1. Why can PHP array keys change type unexpectedly?

  2. How do array_merge() and the array union operator differ?

  3. How should you choose a PHP array sorting function?

  4. Why can a filtered PHP list become a JSON object?

  5. What should a PHP developer know about strings and Unicode?

  6. Why is adding 24 hours not always the same as moving to the next local calendar day?

  7. Why is DateTimeImmutable often useful in application code?

  8. How can integer validation accidentally reject a valid zero?

  9. How should JSON decoding errors and number limits be handled?

  10. Why map validated input into a DTO or value object?

  11. How do generators reduce memory use, and when do they not help?

  12. Why should an API distinguish an iterable from a reusable collection?

  13. What are PHP attributes used for?

  14. What do covariance and contravariance mean for PHP method signatures?

  15. How do self and static differ in inherited static behavior?

  16. What does cloning an object copy?

  17. When can magic methods make an API harder to maintain?

  18. Why should modern PHP code avoid accidental dynamic properties?

  19. What do property hooks add in PHP 8.4?

  20. When is a static closure useful?

  21. How do PDO prepared statements help prevent SQL injection?

  22. How should an API safely support a user-selected sort column?

  23. How should a PDO transaction be structured around several related writes?

  24. Why does a transaction alone not prevent a lost update?

  25. How do bindParam() and bindValue() differ?

  26. How should PDO failures be translated into application errors?

  27. How should passwords be stored and verified in PHP?

  28. How can password hashes be upgraded without forcing every user to reset immediately?

  29. Which session settings should be considered for an authenticated PHP application?

  30. How should an application address session fixation during login?

  31. How should a state-changing form defend against CSRF?

  32. Why must authorization be checked after authentication?

  33. How should PHP file uploads be handled safely?

  34. How should a PHP application prevent path traversal in file access?

  35. What makes server-side URL fetching risky in PHP?

  36. How should a PHP application invoke an external program safely?

  37. How do composer install and composer update differ?

  38. How should development dependencies be handled in deployment?

  39. How does dependency injection improve PHP tests?

  40. When should a PHP database test use a real database rather than a mock?

PHP Interview Questions for Experienced

Use these scenarios to assess production diagnosis, concurrency, deployment and recovery. Strong candidates should connect PHP’s process lifecycle to data integrity and operational constraints.

  1. How would you diagnose a slow PHP endpoint before changing code?

  2. What does OPcache optimize, and what does it not cache?

  3. When might PHP's JIT help, and why should it be benchmarked?

  4. How does preloading differ from ordinary OPcache behavior?

  5. How would you choose an FPM worker count?

  6. Why can persistent database connections be risky in a worker pool?

  7. What changes when PHP code runs in a long-lived worker instead of a fresh request lifecycle?

  8. How would you investigate growing memory use in a PHP worker?

  9. What do fibers provide, and what do they not provide automatically?

  10. How would you prevent an asynchronous PHP service from creating unbounded work?

  11. How would you make a queue consumer safe when a job can be delivered more than once?

  12. Why is an outbox useful when a PHP transaction must publish an event?

  13. How should a PHP API implement an idempotency key for a state-changing request?

  14. How would you handle deadlocks without retrying unsafe work?

  15. Why can PHP sessions serialize otherwise independent requests?

  16. How would you design logout and session revocation across several devices?

  17. Why should untrusted data not be passed to unserialize()?

  18. How should a webhook signature be verified in PHP?

  19. How should a PHP service compare secrets or authentication tokens?

  20. How would you stream a large response without loading it all into memory?

  21. What causes headers already sent errors, and how should they be fixed?

  22. How would you plan a PHP version upgrade safely?

  23. How should a library declare and test its supported PHP versions?

  24. Why should PHP version and extension checks happen in the deployment environment?

  25. How should environment configuration and secrets be handled in PHP?

  26. How would you make a PHP deployment compatible with a rolling database migration?

  27. How would you assess whether a cache improves a PHP application correctly?

  28. What makes a cache stampede different from an ordinary cache miss?

  29. How should logs and traces support PHP incident investigation without leaking data?

  30. How would you choose between exceptions and explicit result objects for a domain operation?

  31. How can static analysis complement PHP runtime tests?

  32. How should a team decide whether to adopt PHP 8.4 property hooks in an existing API?

  33. What does the PHP 8.5 pipe operator do, and when is it useful?

  34. How would you review a PHP package before introducing it into a sensitive service?

  35. How would you investigate an intermittent PHP bug caused by shared state?

  36. How would you design cancellation and cleanup for a PHP background job?

  37. How should a PHP service handle a timeout after sending a payment request?

  38. How would you refactor a legacy PHP script without rewriting everything at once?

  39. How should a PHP team handle a security patch that could change application behavior?

  40. What would demonstrate senior PHP engineering judgment in an interview?

PHP Interview Questions and Answers

The answers follow the same order as the question bank. Look for a direct explanation, a practical consequence and an understanding of limits.

PHP Interview Questions and Answers for Beginners

These answers establish the language and request-handling foundations. Use small changes to an example to check whether the candidate understands why its behavior changes.

1. What is PHP, and where does it run in a web application?

PHP is a general-purpose language commonly executed on a server to generate responses, process requests and interact with services. In a typical web application, the browser receives HTML, JSON or another response format, not the PHP source. PHP also runs command-line scripts and long-running applications, so it is not limited to embedding code in HTML.

For a product page, PHP might load product data and render a template before the server returns it. JavaScript in the browser can then add client-side interaction. The distinction matters when debugging: a browser console cannot directly inspect a server-side variable, and exposing source files through an incorrectly configured server is a deployment problem rather than normal PHP behavior.

2. How does a typical PHP-FPM request reach application code?

A web server receives the HTTP request and, for the configured PHP entry point, forwards it to PHP-FPM through FastCGI. An FPM worker executes the application and returns response headers and content. The web server usually handles static assets separately. Routing inside a framework occurs after this infrastructure has selected the application entry point.

I would check web-server routing, the script path, FPM availability and application logs when a request fails. These layers can produce different errors: a gateway failure need not mean the PHP code threw an exception. A correct deployment should expose only the intended public directory, keeping configuration, dependencies and private files outside direct web access.

3. Why do PHP-only files usually omit the closing PHP tag?

A PHP-only file starts with <?php and can omit the closing tag. Omitting it reduces the risk of accidentally sending whitespace or other output after the tag. Unexpected output can interfere with headers, cookies or a response body that must contain valid JSON.

This convention is especially useful in library and configuration files that are included by other code. It does not replace proper output discipline: a debugging print inside the file still sends content. Files that intentionally mix PHP and HTML may use closing tags as part of their template structure, so the rule concerns PHP-only source files rather than every possible PHP document.

4. How do variables and constants differ in PHP?

Variables use a dollar prefix and hold values that can change during execution. Constants represent named values that cannot be reassigned once defined in their applicable scope. Class constants can express values associated with a type, while ordinary local variables carry the changing state of a computation.

I would use a constant for a stable domain label or a deliberately fixed limit, and a variable for a user's current request value. A constant is not a secure place to store a secret merely because it cannot be reassigned. Configuration and credentials still require appropriate storage, access control and handling, and environment-dependent settings should not be confused with universal business constants.

5. Which basic value types should a PHP developer understand?

Core values include booleans, integers, floating-point numbers, strings, arrays, objects, null and resources. Modern PHP also supports rich type declarations, but the runtime value and the declared contract are related concepts rather than identical ones. An array is an ordered map, not a separate fixed-size vector type.

The distinction matters when values cross a boundary. Query parameters commonly arrive as strings or arrays even when an application expects an integer. A database driver may also return numeric data as strings depending on its configuration. I would inspect and validate the input representation before applying domain rules, rather than assume a value has the right type because it looks numeric when printed.

6. How do loose equality and strict equality differ?

Loose equality, ==, compares values using PHP's comparison and conversion rules. Strict equality, ===, requires the same type as well as the same value. Strict comparison is often clearer when a return value can be a valid zero or a failure indicator.

For example, a string search can return integer zero when a match begins at the first character and boolean false when no match exists. Checking the result with === false preserves that distinction. Loose-comparison behavior has changed across PHP versions, so an interview should use the stated runtime rather than repeat legacy examples as universal rules. Strict equality does not itself validate untrusted input.

PHP 8.2+ — a match at offset zero is not failure

<?php
$position = strpos('alpha', 'a');
if ($position === false) {
    echo "Not found\n";
} else {
    echo "Found at offset {$position}\n";
}
// Expected: Found at offset 0
<?php
$position = strpos('alpha', 'a');
if ($position === false) {
    echo "Not found\n";
} else {
    echo "Found at offset {$position}\n";
}
// Expected: Found at offset 0
<?php
$position = strpos('alpha', 'a');
if ($position === false) {
    echo "Not found\n";
} else {
    echo "Found at offset {$position}\n";
}
// Expected: Found at offset 0

7. Why should money usually not be calculated with ordinary floating-point values?

Binary floating-point cannot represent many decimal fractions exactly. Repeated calculations and rounding can produce small discrepancies, which become important when amounts must reconcile or follow a specified rounding policy. The problem is representation and arithmetic, not a PHP-specific failure to perform addition.

For a currency with a known minor unit, integer minor-unit amounts can be appropriate within checked range limits. Other applications need a decimal library or extension and an explicit scale and rounding rule. I would avoid assuming every currency has two decimal places or converting through a float before creating a decimal value, since that can import the very approximation the decimal representation was intended to avoid.

8. How do single-quoted and double-quoted strings differ?

Double-quoted strings support variable interpolation and a broader set of escape sequences. Single-quoted strings perform much less interpretation, with special handling for an escaped quote and backslash. The choice should make the intended text clear rather than rely on an unmeasured performance assumption.

For a message containing a variable, double quotes can be convenient; for a regular expression or literal text with dollar signs, single quotes may reduce accidental interpretation. Neither quoting style makes output safe for HTML or SQL. Escaping a PHP string literal is a source-code concern, while encoding data for a browser or binding a database parameter addresses a different boundary.

9. What is unusual about PHP arrays compared with arrays in some other languages?

A PHP array is an ordered map whose keys are integers or strings. It can represent a list, dictionary or mixed structure, but key conversion rules and memory overhead matter. Values can have different types, which is flexible but requires a clear contract when an array represents a domain record.

For example, a sequential list of names and a map from user IDs to names are both arrays, yet functions that reindex keys can affect them differently. I would choose an explicit value object or typed class when a record's fields and invariants need stronger guarantees. Calling everything an array should not hide whether ordering, key identity or a particular shape is required.

10. How do isset(), array_key_exists() and empty() answer different questions?

isset() checks that a variable or element exists and is not null. array_key_exists() checks whether the specified key exists in an array even when its value is null. empty() combines absence with PHP's false-like value rules, so it also treats values such as zero and the string "0" as empty.

These differences matter for an API field that may be explicitly set to null or a quantity that may validly be zero. I would choose the check based on the contract rather than use empty() for every validation step. Presence, nullability, type and domain validity are separate questions that may need separate checks.

Input element

isset()

array_key_exists()

empty()

Missing key

false

false

true

Key with null

false

true

true

Key with integer 0

true

true

true

Key with string "0"

true

true

true

Key with string "hello"

true

true

false

11. What does the null coalescing operator do?

The ?? operator returns its left operand when it exists and is not null; otherwise it evaluates and returns the fallback. It is useful for optional array keys without producing an undefined-key warning for the missing access. It follows isset-like semantics, so an explicit null selects the fallback too.

For an optional display theme, $input['theme'] ?? 'light' can be appropriate. It will not replace an empty string, false or zero merely because those values are false-like. If null has a distinct business meaning, use a presence check and explicit handling instead. A convenient fallback should not silently convert malformed mandatory input into a valid-looking default.

12. How do foreach loops behave when iterating by reference?

A normal foreach gives the loop variable the current value for each iteration. Using a reference allows changes through that variable to modify the corresponding array element. After a reference loop, the variable can remain a reference to the last element unless the reference is explicitly broken.

That lingering reference can cause a later assignment or loop to modify data unexpectedly. I would use by-reference iteration only when mutation is intended and call unset($value) after the loop. Often building a new result array is easier to reason about. The choice should reflect the required ownership and mutation behavior, not a blanket belief that references are always faster.

PHP 8.2+ — break the reference after intentional mutation

<?php
$values = [1, 2, 3];
foreach ($values as &$value) {
    $value *= 2;
}
unset($value);
foreach ($values as $value) {
    // Reading through an ordinary loop must not rewrite the last element.
}
echo json_encode($values, JSON_THROW_ON_ERROR), "\n";
// Expected: [2,4,6]
<?php
$values = [1, 2, 3];
foreach ($values as &$value) {
    $value *= 2;
}
unset($value);
foreach ($values as $value) {
    // Reading through an ordinary loop must not rewrite the last element.
}
echo json_encode($values, JSON_THROW_ON_ERROR), "\n";
// Expected: [2,4,6]
<?php
$values = [1, 2, 3];
foreach ($values as &$value) {
    $value *= 2;
}
unset($value);
foreach ($values as $value) {
    // Reading through an ordinary loop must not rewrite the last element.
}
echo json_encode($values, JSON_THROW_ON_ERROR), "\n";
// Expected: [2,4,6]

13. What is the scope of a variable inside a PHP function?

A named function has its own local variable scope. Variables defined outside it are not automatically visible inside, apart from superglobals and explicitly accessed mechanisms. Parameters and return values provide a clearer interface than relying on global state.

For a price calculation, I would pass the amount and discount policy into the function rather than read a mutable global discount. That makes dependencies visible and testing easier. Declaring a variable global links the function to the global symbol, but it also creates coupling. The fact that PHP permits this pattern does not make it the best design for reusable application logic.

14. How do passing by value and passing by reference differ?

Passing by value gives the function a value it can use without reassigning the caller's variable. A by-reference parameter allows assignments through the parameter to change that caller variable. PHP uses implementation techniques such as copy-on-write for arrays and strings, so passing by value does not always mean an immediate deep copy.

Objects need a separate explanation: a copied object value still identifies the same object, so mutating its properties can be visible to the caller without a reference parameter. Reassigning the local parameter to a different object is different. I would explain these behaviors explicitly before choosing references as an attempted optimization.

15. What do parameter and return type declarations provide?

Type declarations specify the values a function accepts and returns, allowing PHP to reject incompatible values according to its type rules. They document a useful runtime contract and support static analysis. They do not express every business invariant, such as a positive amount or a valid email address.

A function accepting an integer quantity can still receive a negative integer unless it checks that rule. I would validate external representations at the boundary and then use types to keep internal interfaces clear. The project's coercion policy and PHP version also matter; adding a type declaration is not a substitute for understanding how calls from different files are handled.

16. What does declare(strict_types=1) change?

Strict typing changes how scalar type declarations are enforced for calls made from the declaring file. It does not globally convert PHP into a language without coercion, and it does not automatically validate HTTP input. The caller's file is important for parameter checking; putting a declaration only in the function's file does not make every external call strict.

In a strict call, passing a numeric string to an integer parameter raises a TypeError, while an integer can still satisfy a float parameter. Return declarations have their own enforcement context. I would apply a consistent project convention and parse external data deliberately rather than rely on implicit conversion to implement validation.

PHP 8.2+ — strictness at the call site

<?php
declare(strict_types=1);
function increment(int $value): int {
    return $value + 1;
}
echo increment(2), "\n"; // 3
try {
    increment('2');
} catch (TypeError $error) {
    echo "Numeric string rejected\n";
}
<?php
declare(strict_types=1);
function increment(int $value): int {
    return $value + 1;
}
echo increment(2), "\n"; // 3
try {
    increment('2');
} catch (TypeError $error) {
    echo "Numeric string rejected\n";
}
<?php
declare(strict_types=1);
function increment(int $value): int {
    return $value + 1;
}
echo increment(2), "\n"; // 3
try {
    increment('2');
} catch (TypeError $error) {
    echo "Numeric string rejected\n";
}

17. How do nullable and union types differ?

A nullable type permits a specified type or null, such as ?User. A union permits one of several types, such as int|string. They can make an interface more accurate, but an overly broad union can shift ambiguity into every caller.

For a lookup, ?User may clearly mean that no matching user was found. A function returning User|false|string for several unrelated outcomes is harder to use safely. I would consider a dedicated result type or exceptions where appropriate, and state whether absence is expected behavior or a failure. Type syntax should clarify the API's meaning rather than merely describe every value it has ever returned.

18. How do void and never return types differ?

A void function completes without returning a meaningful value. A never function does not return normally at all, for example because it always throws or terminates execution. The distinction helps both readers and analysis tools understand whether subsequent code is reachable.

A logging method can be void because the caller continues afterward. A helper that always throws a domain exception can be never. I would not label a function never simply because its current implementation usually fails: every path must satisfy the contract. Terminating an entire request can also be less composable than throwing an exception handled at an application boundary.

19. How do named arguments change an API's compatibility concerns?

Named arguments allow callers to identify parameters by name rather than position. This can make calls with several optional parameters more readable, but it means parameter names become part of the interface callers may depend on. Renaming a public parameter can therefore break consumers even when its position and type stay unchanged.

I would choose clear parameter names and consider named-argument usage when evolving a library. Named arguments do not remove ordering rules or permit arbitrary unknown names. For application code, they are useful when the name communicates intent; they should not be used to make a poorly designed function with many unrelated options appear simpler than it is.

20. What are variadic parameters useful for?

A variadic parameter collects additional arguments into an array, allowing a function to accept a variable number of inputs. Type declarations can constrain each supplied value. Variadics suit operations such as summing amounts or combining a set of criteria when the API genuinely accepts an open-ended collection.

I would distinguish variadic calls from passing one array: argument unpacking with ... expands a collection into arguments, while an ordinary array argument remains one value. Named arguments and string keys can affect unpacking behavior, so the expected collection shape matters. For a large or streaming dataset, accepting an iterable can be more suitable than collecting every argument eagerly.

21. How do closures capture variables from their surrounding scope?

An ordinary closure can explicitly capture variables with use. Capturing by value preserves the value at creation, while capturing by reference connects the closure to the variable's subsequent state. Objects captured by value still refer to the same object unless separately cloned.

For a callback that applies a fixed discount, value capture makes the chosen discount clear. Reference capture may be useful for an intentional accumulator, but it can create surprising coupling if the surrounding variable changes later. I would also consider how long the closure lives, since captured objects can keep large structures or request-specific data reachable longer than expected.

22. How are arrow functions different from ordinary anonymous functions?

Arrow functions use the concise fn syntax for a single expression and automatically capture used outer variables by value. They are useful for small transformations where a full block would add noise. They are not a replacement for a multi-step function with validation, branches and several statements.

For mapping a list of prices to adjusted prices, an arrow function can show the transformation clearly. If the operation needs error handling or side effects, an ordinary closure may be easier to read. Automatic value capture does not imply deep immutability: a captured object can still be mutated through its methods or properties.

23. What does match improve compared with switch?

A match expression compares using strict identity, returns a value and does not fall through between arms. If no arm matches and no default exists, it throws an UnhandledMatchError. A switch statement uses different comparison behavior and commonly requires explicit control of fall-through.

Match suits mapping a known status or enum case to an output. Its exhaustiveness can help reveal a newly added state, but a broad default can hide that benefit. I would choose it for expression-oriented decisions and use ordinary control flow when the branches perform substantial work, rather than force a large process into an unreadable expression.

PHP 8.2+ — strict match arms return a value

<?php
function describe(int|string $value): string {
    return match ($value) {
        0 => 'integer zero',
        '0' => 'string zero',
        default => 'other',
    };
}
echo describe(0), "\n", describe('0'), "\n";
// Expected lines: integer zero; string zero
<?php
function describe(int|string $value): string {
    return match ($value) {
        0 => 'integer zero',
        '0' => 'string zero',
        default => 'other',
    };
}
echo describe(0), "\n", describe('0'), "\n";
// Expected lines: integer zero; string zero
<?php
function describe(int|string $value): string {
    return match ($value) {
        0 => 'integer zero',
        '0' => 'string zero',
        default => 'other',
    };
}
echo describe(0), "\n", describe('0'), "\n";
// Expected lines: integer zero; string zero

24. What does the nullsafe operator protect against?

The nullsafe operator, ?->, allows a property or method access chain to short-circuit when the receiver is null. It is useful when absence is an expected part of the model. It does not catch exceptions thrown by a method or treat every invalid receiver as null.

For an optional customer address, a nullsafe chain can produce null when the customer or address is absent. If the address is mandatory for checkout, silently returning null may conceal an invariant violation. I would distinguish optional navigation from error handling and ensure the caller deliberately handles the resulting nullable value.

25. How do include and require differ?

Both evaluate another PHP file in the relevant scope, but failure to load the file is handled differently: include emits a warning and can continue, while require raises an Error in modern PHP. Their once variants avoid including the same file more than once during that execution context.

A mandatory bootstrap should not silently proceed when missing. I would normally use Composer autoloading for classes instead of manually requiring each class file. Include paths must not be built directly from untrusted input, since loading a user-selected file can turn a routing or template convenience into code execution. Clear entry points and known paths are easier to audit.

26. What problem do namespaces solve?

Namespaces organize names such as classes, interfaces and functions so independently developed code can coexist without naming collisions. An import with use provides a local name or alias; it does not itself load the class or import all runtime state from another module.

Two packages can each define a class named Client under different namespaces. I would use explicit imports and a predictable directory layout to keep references understandable. Autoloading resolves how class definitions become available, while namespaces resolve which name is intended. Confusing these mechanisms can lead to debugging the directory structure when the actual problem is an incorrect imported name.

27. How does Composer help a PHP application?

Composer manages package dependencies and generates an autoloader based on package configuration. The project declares requirements in composer.json, while the lock file records a resolved dependency set. This supports reproducible installations when the required PHP version and extensions are also satisfied.

I would normally deploy an application's reviewed lock file with an install operation rather than resolve new versions unexpectedly during deployment. Composer does not make every package trustworthy or guarantee application compatibility. Dependency review, security advisories and tests remain necessary, and scripts or plugins can execute code during dependency operations, so those operations belong in a controlled workflow.

28. How does PSR-4 autoloading connect a class name to a file?

PSR-4 maps a namespace prefix to one or more base directories, then translates the remaining namespace and class name into a relative file path. Composer can generate an autoloader for that mapping. It removes the need for explicit include statements throughout application code.

With a prefix App\ mapped to src/, App\Service\Mailer corresponds to a matching path under src/Service/Mailer.php. Case consistency matters, especially when moving from a case-insensitive development filesystem to a case-sensitive deployment. Autoloading does not validate the class's behavior; it only arranges loading according to the configured naming convention.

29. What is the difference between a class and an object?

A class defines a type's structure and behavior, while an object is a runtime instance with its own state. Methods can enforce operations over that state, making a class more than a container for public fields. Object design should express meaningful responsibilities rather than mirror every database table automatically.

For example, a Money value object can require a currency and a valid amount and provide explicit comparison or addition behavior. Two instances may hold equal values without being the same object. I would distinguish value equality from object identity when designing caches, comparisons and tests, rather than assume matching printed properties means two references identify one instance.

30. How do public, protected and private visibility differ?

Public members are accessible through the public interface. Protected members are available within the class and its inheritance hierarchy, while private members are restricted to the declaring class's scope. Visibility helps control how state is accessed, but it is not a security boundary against malicious code running with the application's privileges.

I would keep implementation details private and expose operations that preserve invariants. Making every property public can let callers put an object into an invalid state. Protected access can help extension points, but it also couples subclasses to internals, so composition or a narrower interface may provide a more stable design.

31. When should an interface be preferred to an abstract class?

An interface defines a contract that different implementations can satisfy. An abstract class can also share implementation and state through inheritance. The decision depends on whether the design needs interchangeable behavior or a common implementation relationship, not on a rule that one is always more object-oriented.

For a payment gateway boundary, an interface can let production and test implementations share a contract without sharing a base class. An abstract class may suit a carefully designed family with common behavior. I would avoid forcing unrelated classes into an inheritance hierarchy merely to reuse a helper method, since that creates stronger coupling than composition.

32. What are traits, and what problems can they introduce?

Traits provide reusable method implementations that classes can compose without ordinary multiple class inheritance. They can reduce duplication when the shared behavior is cohesive. They do not establish a substitutable type contract in the same way an interface does.

Conflicting method names need explicit resolution, and traits that assume hidden properties or other methods can make a class difficult to understand. I would keep their dependencies clear and consider an injected collaborator when the behavior has its own state or lifecycle. Reusing code is valuable, but scattering a class's essential behavior across many traits can make changes and debugging harder.

33. What does constructor property promotion do?

Constructor property promotion combines a constructor parameter with a property declaration and assignment. It reduces repetitive setup for objects whose dependencies or values are supplied at construction. Visibility and type information appear directly in the constructor signature.

It does not validate domain rules automatically or replace the need for a clear object lifecycle. A promoted integer amount can still be invalid for the domain. I would use promotion for straightforward dependencies and value fields, then add explicit validation where needed. A very large promoted constructor can still indicate that the class has too many responsibilities.

34. What does readonly mean for a property or class?

Readonly restricts reassignment of the property after its permitted initialization under the relevant PHP version's rules. A readonly class applies related restrictions across its declared instance properties. This supports value-oriented designs but does not make the entire object graph deeply immutable.

A readonly property that holds another object can still refer to an object whose internal state changes. I would use immutable collaborators or defensive copying when the domain needs stronger guarantees. Version-specific cloning and initialization rules matter, so a migration should check the targeted PHP release rather than assume every readonly behavior has been identical since the feature first appeared.

35. When are enums better than loose strings?

Enums define a finite set of named cases, preventing arbitrary strings from being treated as valid states. Backed enums associate cases with integer or string values useful at storage and transport boundaries. They can also carry behavior through methods.

An order status enum makes impossible spellings harder to introduce internally. External input still needs conversion and validation: tryFrom() can express an unknown backed value as null, while from() throws for an invalid backing value. I would not use an enum for an open-ended set maintained by users, where new values should not require a code release.

36. How do exceptions and PHP Error objects relate?

Both Exception and Error implement Throwable, so a suitable boundary can catch either. Exceptions often represent application or library failures, while Error subclasses include problems such as TypeError. This does not mean every failure should be caught and ignored.

I would catch a specific recoverable exception where the application has a meaningful response, and use a top-level handler to log unexpected failures and produce a safe response. Returning a fake success after catching Throwable can hide defects and corrupt workflows. Warnings are another mechanism and are not automatically Throwable objects, so error-handling policy should distinguish them clearly.

37. What is finally useful for?

A finally block runs when control leaves the associated try/catch structure through ordinary language control flow, including many return and exception paths. It is useful for cleanup such as closing a resource. It does not guarantee execution after every possible process termination or infrastructure failure.

I would avoid returning from finally because that can override an earlier return or exception and make failures disappear. Cleanup should also not casually replace the original error with a secondary one. Durable business actions should not rely solely on a finally block running; transaction design and recovery procedures must account for crashes and abrupt termination.

38. How should a PHP endpoint read and validate incoming data?

It should determine the expected content type and shape, parse the input with error handling, then validate types, required fields and domain rules. PHP superglobals are convenient representations, not trusted typed objects. Query and form inputs can be arrays where a string was expected, so shape checks matter before calling string functions.

For a positive integer ID, I would reject arrays, invalid representations and values outside the accepted range rather than cast arbitrary text to an integer. JSON bodies require reading and decoding the body explicitly in a suitable endpoint. Validation should produce a consistent client error while preserving a distinction between bad input and an internal application failure.

39. Why must output escaping match its destination context?

Data safe for one context can be unsafe in another. HTML text, HTML attributes, JavaScript, URLs and SQL have different rules. For ordinary HTML text or quoted attribute values, correctly configured htmlspecialchars() can encode special characters, but it is not a universal sanitizer for every output destination.

I would keep raw domain data separate from presentation encoding and use a template engine's context-appropriate escaping where possible. URL schemes still need validation, and embedding data in script requires an appropriate serialization strategy. Escaping input once at collection time can lead to double encoding and still fail when the same value is later used in a different context.

40. How should application errors be exposed in development and production?

Development needs detailed diagnostics, while production responses should avoid leaking stack traces, credentials, queries or filesystem paths. Errors should still be recorded in appropriately protected logs with enough context for investigation. Hiding the response does not justify suppressing the evidence entirely.

I would configure reporting and display behavior deliberately for each environment and assign a correlation identifier to unexpected failures. Logs should exclude secrets and unnecessary personal data. A user-facing generic error can be paired with a detailed internal record, allowing support and engineering to investigate without turning the public response into a disclosure channel.

PHP Interview Questions and Answers for Intermediate

These answers connect PHP APIs to concrete correctness and security decisions. Pay attention to data shape, driver behavior, version requirements and the distinction between parsing and validation.

41. Why can PHP array keys change type unexpectedly?

PHP arrays accept integer and string keys, but certain supplied keys are converted according to documented rules. A valid decimal integer string such as "8" can become integer 8, while a string such as "08" remains a string. Booleans and null also undergo key conversion. Different inputs can therefore address the same element.

I would not use loosely specified external identifiers as array keys without checking their representation. A map keyed by account IDs should preserve the intended distinction between an identifier and a number. If both integer 8 and string "8" are expected to represent different things, a PHP array needs an explicit encoding strategy or a different structure rather than assuming those keys remain distinct.

42. How do array_merge() and the array union operator differ?

array_merge() appends and renumbers numeric-keyed values, while later string-keyed values replace earlier ones with the same key. The array union operator, +, preserves entries from the left array when a key already exists and adds only missing keys from the right. They implement different policies, not interchangeable syntax for combining arrays.

For defaults, union can preserve user-supplied keys, but it also preserves an explicit null. For a list of items, merge may be appropriate because numeric indices are not meaningful identities. I would state whether the operation combines lists, overlays settings or merges records; recursively merging arbitrary configuration requires an even more explicit conflict policy.

Operation

Duplicate string key

Numeric keys

array_merge($left, $right)

Right value replaces left

Values appended and numeric keys renumbered

$left + $right

Left value retained

Existing left keys retained; only absent right keys added

43. How should you choose a PHP array sorting function?

Choose based on whether you are sorting values or keys, whether key associations must survive, and whether comparison needs custom domain rules. For example, sort() reindexes values, while asort() preserves key associations and ksort() sorts by key. Custom comparator functions should provide a consistent ordering.

A user-ID map should not lose its IDs just because its names are sorted. Likewise, sorting numeric-looking strings lexically can differ from numeric ordering. I would make the comparison mode explicit and include a deterministic tie-breaker where downstream pagination or reproducibility requires one, instead of depending accidentally on the input order.

Intent

Typical function

Key behavior

Sort values as a list

sort()

Reindexes keys

Sort values while retaining a map

asort()

Preserves associations

Sort by keys

ksort()

Orders the keys

Custom value comparison for a list

usort()

Reindexes keys

44. Why can a filtered PHP list become a JSON object?

A PHP array encodes as a JSON array when its keys form a continuous sequence starting at zero. Filtering commonly preserves original keys, so removing an element can leave gaps and cause JSON encoding to produce an object instead. The values may look correct while the API's shape has changed.

If the result is semantically a list, array_values() can reindex it before encoding. If the keys are meaningful identifiers, removing them would be wrong. I would test the serialized response shape as part of the API contract, especially for empty results and filtered lists, rather than only assert that the expected values appear somewhere in the output.

PHP 8.2+ — preserve a JSON list after filtering

<?php
$values = [10, 20, 30];
$filtered = array_filter($values, static fn(int $n): bool => $n >= 20);
echo json_encode($filtered, JSON_THROW_ON_ERROR), "\n";
echo json_encode(array_values($filtered), JSON_THROW_ON_ERROR), "\n";
// Expected: {"1":20,"2":30}
// Then: [20,30]
<?php
$values = [10, 20, 30];
$filtered = array_filter($values, static fn(int $n): bool => $n >= 20);
echo json_encode($filtered, JSON_THROW_ON_ERROR), "\n";
echo json_encode(array_values($filtered), JSON_THROW_ON_ERROR), "\n";
// Expected: {"1":20,"2":30}
// Then: [20,30]
<?php
$values = [10, 20, 30];
$filtered = array_filter($values, static fn(int $n): bool => $n >= 20);
echo json_encode($filtered, JSON_THROW_ON_ERROR), "\n";
echo json_encode(array_values($filtered), JSON_THROW_ON_ERROR), "\n";
// Expected: {"1":20,"2":30}
// Then: [20,30]

45. What should a PHP developer know about strings and Unicode?

A PHP string is a sequence of bytes; ordinary byte-oriented functions do not automatically count user-perceived characters. UTF-8 text can use multiple bytes per code point, and a visible character can consist of several code points. The correct operation depends on whether the task concerns bytes, code points or grapheme clusters.

For a byte limit imposed by a protocol, byte length may be correct. For a user-visible truncation, multibyte or grapheme-aware functions may be needed, with the relevant extension available. I would define the encoding and normalization policy at boundaries and avoid slicing arbitrary bytes in the middle of a multibyte sequence. A database column's character limit also need not equal its storage-byte limit.

46. Why is adding 24 hours not always the same as moving to the next local calendar day?

A local calendar day can be shorter or longer than 24 elapsed hours when daylight-saving transitions occur. An elapsed duration and a calendar operation therefore express different requirements. Timezone rules also vary by location and can change, so a fixed numeric offset is not a complete representation of a named timezone.

For a recurring 9 a.m. appointment, I would calculate the next local date in the intended timezone. For a token valid for exactly 86,400 seconds, I would use an elapsed-time rule. Tests should cover a transition and ambiguous or nonexistent local times, rather than assume a calculation that works in UTC automatically satisfies a calendar scheduling requirement.

47. Why is DateTimeImmutable often useful in application code?

DateTimeImmutable returns a new object for modifying operations rather than mutating the original instance. This helps avoid accidental changes when the same date object is shared between calculations. It does not decide the correct timezone or business calendar rule for the application.

For example, calculating a due date from an invoice date should not silently change the invoice date itself. I would capture the returned value and use explicit timezone and parsing rules. Ignoring the returned object is a common mistake because the original remains unchanged. Immutability improves reasoning, but invalid input and daylight-saving assumptions still require deliberate handling.

48. How can integer validation accidentally reject a valid zero?

A validation function may return integer zero for valid input and boolean false for invalid input. A loose false-like check collapses those outcomes. The application should compare the failure result strictly and then apply the domain's allowed range separately.

For a pagination offset, zero is valid; for a strictly positive quantity, zero may be invalid for a different reason. I would also reject arrays before scalar validation and consider input-size and range limits. Casting a string to int is not equivalent to validating its syntax, and a null result from a missing input should not be mistaken for the same condition as a malformed supplied value.

PHP 8.2+ — valid zero and invalid input follow different paths

<?php
declare(strict_types=1);
function parseOffset(mixed $raw): int {
    if (!is_string($raw)) {
        throw new InvalidArgumentException('Offset must be a string');
    }
    $value = filter_var($raw, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 0, 'max_range' => 10000],
    ]);
    if ($value === false) {
        throw new InvalidArgumentException('Invalid offset');
    }
    return $value;
}
echo parseOffset('0'), "\n"; // 0
try {
    parseOffset('abc');
} catch (InvalidArgumentException $error) {
    echo "Rejected\n";
}
<?php
declare(strict_types=1);
function parseOffset(mixed $raw): int {
    if (!is_string($raw)) {
        throw new InvalidArgumentException('Offset must be a string');
    }
    $value = filter_var($raw, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 0, 'max_range' => 10000],
    ]);
    if ($value === false) {
        throw new InvalidArgumentException('Invalid offset');
    }
    return $value;
}
echo parseOffset('0'), "\n"; // 0
try {
    parseOffset('abc');
} catch (InvalidArgumentException $error) {
    echo "Rejected\n";
}
<?php
declare(strict_types=1);
function parseOffset(mixed $raw): int {
    if (!is_string($raw)) {
        throw new InvalidArgumentException('Offset must be a string');
    }
    $value = filter_var($raw, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 0, 'max_range' => 10000],
    ]);
    if ($value === false) {
        throw new InvalidArgumentException('Invalid offset');
    }
    return $value;
}
echo parseOffset('0'), "\n"; // 0
try {
    parseOffset('abc');
} catch (InvalidArgumentException $error) {
    echo "Rejected\n";
}

49. How should JSON decoding errors and number limits be handled?

Use explicit error handling, such as JSON_THROW_ON_ERROR, so malformed input does not look like a legitimate null result. Then validate the decoded structure and fields. Successful JSON parsing establishes syntax, not authorization, field semantics or a safe payload size.

Large numeric identifiers deserve special attention because conversion to floating-point can lose precision. A contract may represent them as strings, and JSON_BIGINT_AS_STRING can help preserve large integer values during decoding. I would also set appropriate depth and request-size limits. A valid top-level scalar is legal JSON but may still be invalid for an endpoint expecting an object with specific fields.

PHP 8.2+ — parse JSON separately from validating its schema

<?php
try {
    $data = json_decode('{"count":0}', true, 32, JSON_THROW_ON_ERROR);
    if (!is_array($data) || !array_key_exists('count', $data)
        || !is_int($data['count']) || $data['count'] < 0) {
        throw new InvalidArgumentException('Invalid count');
    }
    echo $data['count'], "\n"; // 0
} catch (JsonException $error) {
    echo "Malformed JSON\n";
}
// The domain validation exception is distinct from a JSON parse failure.
<?php
try {
    $data = json_decode('{"count":0}', true, 32, JSON_THROW_ON_ERROR);
    if (!is_array($data) || !array_key_exists('count', $data)
        || !is_int($data['count']) || $data['count'] < 0) {
        throw new InvalidArgumentException('Invalid count');
    }
    echo $data['count'], "\n"; // 0
} catch (JsonException $error) {
    echo "Malformed JSON\n";
}
// The domain validation exception is distinct from a JSON parse failure.
<?php
try {
    $data = json_decode('{"count":0}', true, 32, JSON_THROW_ON_ERROR);
    if (!is_array($data) || !array_key_exists('count', $data)
        || !is_int($data['count']) || $data['count'] < 0) {
        throw new InvalidArgumentException('Invalid count');
    }
    echo $data['count'], "\n"; // 0
} catch (JsonException $error) {
    echo "Malformed JSON\n";
}
// The domain validation exception is distinct from a JSON parse failure.

50. Why map validated input into a DTO or value object?

A dedicated object can make accepted fields, types and invariants explicit after external data has been parsed and validated. It creates a clear transition from loosely shaped input to application data. The mapping should be deliberate rather than blindly assign every incoming field to an object or persistence model.

For an account update, only approved editable fields should reach the command object; a supplied role or owner ID must not become trusted merely because it is present. Constructor types help but do not express every rule. I would keep transport errors separate from domain failures so the endpoint can return an appropriate response without exposing internal implementation details.

51. How do generators reduce memory use, and when do they not help?

A generator yields values on demand instead of constructing the entire output array before iteration. This can reduce memory when both the producer and consumer process one item at a time. It does not help if the source is already fully loaded or the consumer immediately materializes all yielded values.

For reading a large file, a generator can yield parsed records while retaining only the current buffer. I would close resources reliably and define what happens on malformed records or early termination. The generator also changes execution timing: work and exceptions may occur during iteration rather than when the generator function is initially called.

PHP 8.2+ — iterate records while the caller owns the stream

<?php
function lines($stream): Generator {
    while (($line = fgets($stream)) !== false) {
        yield rtrim($line, "\r\n");
    }
    if (!feof($stream)) {
        throw new RuntimeException('Stream read failed');
    }
}
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
    throw new RuntimeException('Cannot open stream');
}
try {
    fwrite($stream, "first\nsecond\n");
    rewind($stream);
    foreach (lines($stream) as $line) {
        echo $line, "\n";
    }
} finally {
    fclose($stream);
}
// Expected lines: first; second. This tiny fixture is not a memory benchmark.
<?php
function lines($stream): Generator {
    while (($line = fgets($stream)) !== false) {
        yield rtrim($line, "\r\n");
    }
    if (!feof($stream)) {
        throw new RuntimeException('Stream read failed');
    }
}
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
    throw new RuntimeException('Cannot open stream');
}
try {
    fwrite($stream, "first\nsecond\n");
    rewind($stream);
    foreach (lines($stream) as $line) {
        echo $line, "\n";
    }
} finally {
    fclose($stream);
}
// Expected lines: first; second. This tiny fixture is not a memory benchmark.
<?php
function lines($stream): Generator {
    while (($line = fgets($stream)) !== false) {
        yield rtrim($line, "\r\n");
    }
    if (!feof($stream)) {
        throw new RuntimeException('Stream read failed');
    }
}
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
    throw new RuntimeException('Cannot open stream');
}
try {
    fwrite($stream, "first\nsecond\n");
    rewind($stream);
    foreach (lines($stream) as $line) {
        echo $line, "\n";
    }
} finally {
    fclose($stream);
}
// Expected lines: first; second. This tiny fixture is not a memory benchmark.

52. Why should an API distinguish an iterable from a reusable collection?

An iterable can be traversed, but it does not necessarily support random access, counting without consumption or repeated traversal. A generator is stateful and cannot simply be treated as an array that can be restarted indefinitely. The interface should communicate what consumers may assume.

If a function needs two passes, I would either require a reusable collection, accept a factory that produces a fresh iterator, or explicitly materialize the data with an understood memory cost. Calling a counting routine and then expecting the same stream to start over can lose data or fail. Laziness is useful only when the lifecycle and consumption contract are clear.

53. What are PHP attributes used for?

Attributes attach structured metadata to declarations, which application code or a framework can inspect through reflection. They can describe routing, validation or other configuration, but PHP does not automatically execute every annotated behavior merely because an attribute is present. A consumer must interpret the metadata.

I would distinguish the declaration from the runtime work performed when reflection instantiates an attribute. Repeated reflective discovery can also have a cost, so a framework may cache metadata. Attributes are useful when configuration belongs close to code, but they should not conceal significant side effects or replace clear method contracts with undocumented conventions.

54. What do covariance and contravariance mean for PHP method signatures?

Covariance allows an overriding method to return a more specific type where the language permits it. Contravariance allows it to accept a broader parameter type. These rules preserve substitutability: callers using the parent contract should not receive less than promised or be required to provide a more restrictive input.

If a parent method returns an Animal, a child may return a Dog. A child should not narrow a parameter from Animal to Dog when callers are entitled to pass other animals. I would verify the actual signature rules for interfaces and inheritance rather than remove types to silence an incompatibility, since the error may reveal a genuine design problem.

55. How do self and static differ in inherited static behavior?

self refers to the class scope where it is written, while static supports late static binding based on the called class in the relevant context. This affects factories and inherited methods that need to preserve the concrete subclass. It is a language dispatch distinction, not simply a preference for one spelling.

A factory using new self() can construct the defining class even when invoked through a subclass. new static() can construct the called class, but then subclass constructor compatibility matters. I would use late binding only when the inheritance design supports it, rather than assume every subclass can safely inherit a factory with arbitrary construction requirements.

56. What does cloning an object copy?

The clone operation creates another object with a shallow copy of its properties, followed by applicable cloning behavior. Object-valued properties can still refer to the same nested objects unless the class deliberately clones or replaces them. A new outer identity therefore does not imply an independent entire object graph.

For an order containing a mutable address object, changing that address through the clone may affect the original if they still share it. I would define which components are immutable, shared or independently owned and implement cloning accordingly. Deep copying every reachable object indiscriminately can also be incorrect for resources, identity-bearing entities or cycles.

57. When can magic methods make an API harder to maintain?

Methods such as __get(), __set() and __call() can support dynamic behavior, but they can hide the real set of available members and when work occurs. A property access that triggers a database call is harder to reason about than an explicitly documented operation.

I would use magic behavior only where its contract is clear and tooling can understand the expected interface. It should not turn misspelled names into silent state changes or swallow exceptions. Explicit methods, typed properties and well-defined adapters often make refactoring and static analysis more reliable, while magic remains appropriate for carefully designed infrastructure boundaries.

58. Why should modern PHP code avoid accidental dynamic properties?

Assigning an undeclared property can hide a typo and bypass the intended class contract. Creation of dynamic properties is deprecated for many classes from PHP 8.2, with specified exceptions such as stdClass and classes using supported dynamic mechanisms. The correct response is usually to declare the intended state or redesign the data container.

I would not add an attribute broadly just to silence warnings without understanding the behavior. If the application genuinely stores arbitrary key-value data, an explicit map may communicate that better. Migration tests should exercise writes that occur only on uncommon paths, since a property typo can remain invisible until a specific payload or workflow triggers it.

59. What do property hooks add in PHP 8.4?

Property hooks allow get and set behavior to be defined for non-static properties, including computed or validated access. They can preserve a property-oriented API while adding logic, but a property may be backed by storage or virtual depending on its implementation. The feature requires PHP 8.4 or later.

I would use hooks for a small, predictable transformation or invariant, not to conceal expensive I/O behind a field access. They are incompatible with readonly properties; asymmetric visibility is a separate tool when read and write access need different restrictions. A codebase supporting older PHP versions needs conventional methods or a deliberate minimum-version change rather than unguarded new syntax.

60. When is a static closure useful?

A static closure is not bound to an object instance through $this. It communicates that the callback does not need instance state and can avoid unintentionally retaining an object through that binding. It can still capture explicitly needed values and perform side effects, so static does not mean pure.

For a transformation callback, a static closure can make the dependency on a supplied configuration value clearer. I would not mark a callback static if it genuinely needs object behavior. In a long-lived process, checking what closures retain can help diagnose memory growth, but changing syntax alone does not remove every captured reference or cache.

61. How do PDO prepared statements help prevent SQL injection?

Prepared statements separate the SQL structure from supplied data values. Parameters represent complete data literals, allowing the driver to handle their representation rather than concatenate user input into SQL text. This protects the parameterized values, not arbitrary dynamically constructed parts of the statement.

I would use a unique placeholder for each value where required and configure error handling deliberately. Table names, column names and sort directions cannot be replaced with ordinary value parameters; those require trusted mappings or allowlists. Driver and emulation behavior also matter, so the application should test its actual database configuration rather than assume every PDO driver implements identical semantics.

PHP 8.2+ with PDO_SQLite — parameters remain data

<?php
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
$insert = $pdo->prepare('INSERT INTO people (id, name) VALUES (:id, :name)');
$insert->execute(['id' => 1, 'name' => 'Alice']);
$find = $pdo->prepare('SELECT id FROM people WHERE name = :name');
$find->execute(['name' => "Alice' OR 1=1 --"]);
echo json_encode($find->fetchAll(PDO::FETCH_COLUMN), JSON_THROW_ON_ERROR), "\n";
// Expected: [] — the input is a name value, not executable SQL structure.
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
$insert = $pdo->prepare('INSERT INTO people (id, name) VALUES (:id, :name)');
$insert->execute(['id' => 1, 'name' => 'Alice']);
$find = $pdo->prepare('SELECT id FROM people WHERE name = :name');
$find->execute(['name' => "Alice' OR 1=1 --"]);
echo json_encode($find->fetchAll(PDO::FETCH_COLUMN), JSON_THROW_ON_ERROR), "\n";
// Expected: [] — the input is a name value, not executable SQL structure.
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
$insert = $pdo->prepare('INSERT INTO people (id, name) VALUES (:id, :name)');
$insert->execute(['id' => 1, 'name' => 'Alice']);
$find = $pdo->prepare('SELECT id FROM people WHERE name = :name');
$find->execute(['name' => "Alice' OR 1=1 --"]);
echo json_encode($find->fetchAll(PDO::FETCH_COLUMN), JSON_THROW_ON_ERROR), "\n";
// Expected: [] — the input is a name value, not executable SQL structure.

62. How should an API safely support a user-selected sort column?

Map the external sort option to a small set of trusted SQL fragments defined by the application. A value placeholder cannot stand in for an SQL identifier or keyword. Attempting to quote arbitrary user text as a column name is not a substitute for deciding which columns the API should expose.

For example, a request value of created can map to a known created_at column, and direction can be restricted to ASC or DESC. Unknown choices should be rejected or handled by an explicit default. I would include a stable tie-breaker for pagination and consider whether sorting by the chosen column is operationally affordable as well as syntactically safe.

63. How should a PDO transaction be structured around several related writes?

Begin the transaction, execute the related operations, commit only when all required database changes succeed, and roll back on failure when a transaction is still active. The database and table engine must actually support the required transactional behavior. Some statements can cause implicit commits in particular databases.

I would keep the transaction short and avoid waiting on remote services while holding locks. Sending an email inside the transaction does not make the email roll back if the database fails. When a workflow includes external side effects, use a design such as an outbox or another explicit recovery protocol rather than assume one PDO transaction covers the entire distributed operation.

64. Why does a transaction alone not prevent a lost update?

A transaction groups operations, but the isolation level and update pattern determine what concurrent transactions can observe and overwrite. Two requests can read the same old value and both write a derived replacement, losing one request's change under an unsuitable pattern.

For an increment, an atomic database expression may be appropriate. For editing a record, optimistic version checks can reject a stale update, while row locking may suit a short critical section. I would choose based on the database and workload and test concurrent behavior. Merely wrapping a read-then-write sequence in begin and commit does not establish the desired isolation or business invariant.

65. How do bindParam() and bindValue() differ?

bindParam() binds a variable by reference so its value is read when the statement executes. bindValue() binds the supplied value. This distinction matters when a variable changes between binding and execution or when the caller tries to bind an expression where a reference is required.

For a single execution, passing a parameter array to execute or using bindValue can often make intent simpler. Explicit binding types can matter for driver-specific behavior, such as integer limits, but they should be tested on the target database. I would not use binding as a substitute for validating that a supplied value is permitted by the domain.

66. How should PDO failures be translated into application errors?

The application should preserve the database error for internal diagnosis while exposing a stable, appropriate error to the caller. Exception mode can make failure paths explicit, but not every database exception is a transient outage or a safe candidate for retry. Constraint violations, permission failures and connection problems require different treatment.

I would map expected conflicts deliberately and avoid returning raw SQL or credentials in responses. Transaction state and cleanup need attention before continuing on a reused connection. Retrying the same invalid statement indefinitely can amplify an incident; retries should be limited to understood transient conditions and designed around the possibility that a previous attempt already committed.

67. How should passwords be stored and verified in PHP?

Use the password hashing API, such as password_hash() and password_verify(), with an appropriate supported algorithm and cost policy. Store the resulting hash rather than plaintext or reversibly encrypted passwords. The encoded result carries information needed for verification, and the API generates a salt when used as intended.

I would allocate enough storage for future hash formats and benchmark the cost on deployment hardware. Algorithms have specific limits: bcrypt truncates input beyond 72 bytes, so the application's password policy and chosen algorithm must handle that deliberately. Hashing does not replace rate limiting, secure transport or account recovery controls; those protect different parts of the authentication process.

PHP 8.2+ — hash and verify without storing the plaintext

<?php
$password = 'demonstration-password-only';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo password_verify($password, $hash) ? "Valid\n" : "Invalid\n";
echo password_verify('wrong-password', $hash) ? "Valid\n" : "Invalid\n";
// Expected lines: Valid; Invalid. Do not print passwords or hashes in logs.
<?php
$password = 'demonstration-password-only';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo password_verify($password, $hash) ? "Valid\n" : "Invalid\n";
echo password_verify('wrong-password', $hash) ? "Valid\n" : "Invalid\n";
// Expected lines: Valid; Invalid. Do not print passwords or hashes in logs.
<?php
$password = 'demonstration-password-only';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo password_verify($password, $hash) ? "Valid\n" : "Invalid\n";
echo password_verify('wrong-password', $hash) ? "Valid\n" : "Invalid\n";
// Expected lines: Valid; Invalid. Do not print passwords or hashes in logs.

68. How can password hashes be upgraded without forcing every user to reset immediately?

After a successful password verification, use password_needs_rehash() with the current algorithm and options to determine whether a new hash should be stored. The supplied plaintext is available at that moment, allowing migration to a stronger policy. Failed logins should not trigger replacement with an unverified password.

I would update the hash safely and consider concurrent changes, such as another request resetting the password at the same time. Users who never log in may need a separate policy. The upgrade process should be observable without logging passwords or hashes, and the cost change should be load-tested so improved protection does not unexpectedly overwhelm the authentication service.

69. Which session settings should be considered for an authenticated PHP application?

Use cookie-based session identifiers over HTTPS, enable strict session-ID handling where the save handler supports it, and configure Secure, HttpOnly and an appropriate SameSite policy for the session cookie. These controls address different risks and should be set before the session starts. Storage permissions and session lifetime policies also matter.

HttpOnly limits script access to the cookie but does not neutralize all consequences of cross-site scripting. SameSite can reduce some cross-site request risks but is not a complete authorization or CSRF design. I would test the actual login and cross-site flows, including any federated authentication, instead of copying settings that break a required workflow or leave an unintended exception.

70. How should an application address session fixation during login?

When authentication or privilege level changes, the application should transition to a new session identifier using a deliberate regeneration strategy. This prevents a preexisting identifier from simply becoming an authenticated credential. Strict mode and avoiding session IDs in URLs reduce related risks but do not replace the transition.

Concurrent requests and unreliable networks complicate immediate deletion of the old session. I would follow a tested framework or documented strategy that handles obsolete identifiers, expiry and race conditions while preventing continued privileged use of the old session. Logging in should also reset relevant authentication state rather than preserve arbitrary untrusted session values from before authentication.

71. How should a state-changing form defend against CSRF?

A session-authenticated form should use an appropriate CSRF defense, commonly an unpredictable token tied to the user's session and verified on the state-changing request. The token must be checked before the operation and compared safely. SameSite cookies and origin checks can add protection within a defined browser model.

I would not use GET requests for state changes or assume that being logged in proves the request originated from the application's own page. Tokens should not appear in URLs where they can leak into history or logs. An API authenticated with a non-automatically attached credential has different considerations, so the defense should match the authentication and browser behavior rather than apply one explanation to every endpoint.

72. Why must authorization be checked after authentication?

Authentication establishes an identity; authorization determines whether that identity may perform a particular action on a particular resource. A valid session does not permit access to every record. The check should use trusted server-side ownership, role or policy data rather than accept a user ID or permission flag from the request.

For an invoice endpoint, knowing its numeric ID is not evidence that the caller may read it. I would centralize policy where practical and test both allowed and denied cases, including cross-account access. A hidden button is a user-interface convenience, not enforcement, and fetching a resource before checking access can still leak information through errors or timing.

73. How should PHP file uploads be handled safely?

Validate the upload result and enforce size, type and business restrictions before accepting the file. Do not trust the client-provided filename or content type. Use server-generated storage names and keep uploaded content outside executable web paths, with controlled download behavior when it must be served.

The application should account for PHP and web-server body limits as well as its own checks. A filename extension does not establish the content's safety, and inspecting a MIME type does not prove that a complex document is harmless. I would use the upload-specific move mechanism, constrain processing resources and apply any required scanning or transformation before making the file available.

74. How should a PHP application prevent path traversal in file access?

Prefer mapping an application identifier to a server-owned path rather than accept an arbitrary path from the user. If paths must be resolved, enforce the intended root and access policy with awareness of canonicalization, symbolic links and race conditions. Removing a few suspicious substrings is not a reliable boundary.

For document downloads, the request can provide a record ID whose authorized storage location is retrieved internally. I would also consider stream wrappers and whether the chosen filesystem API accepts URLs. A path that stays inside a directory is not automatically authorized for the current user; containment and resource permissions are separate checks.

75. What makes server-side URL fetching risky in PHP?

An attacker-controlled URL can cause the server to contact internal systems, metadata services or other destinations the attacker cannot reach directly. PHP stream wrappers and HTTP clients provide powerful access mechanisms, so fetching a URL is a network capability, not merely string processing.

I would constrain schemes and destinations, validate resolved addresses, control redirects and apply network-level restrictions as part of a layered design. DNS changes and alternate address representations complicate simplistic checks. Timeouts, response-size limits and content handling also matter. A regular expression that accepts an https prefix does not establish that the eventual destination is safe or authorized.

76. How should a PHP application invoke an external program safely?

Prefer a library or an API that avoids a shell when possible. If a process is necessary, separate the executable and arguments using a suitable process API, restrict allowed operations and avoid building a shell command from untrusted text. Escaping rules vary by platform and shell, so one helper is not a universal safety guarantee.

I would also control working directory, environment, timeouts, output size and permissions. An argument can be syntactically escaped yet still act as a dangerous program option, so domain allowlisting and option handling remain necessary. Process success should be checked through its exit status and expected output rather than assuming that receiving any text means the operation completed correctly.

77. How do composer install and composer update differ?

With a lock file, install uses the recorded dependency versions, while update resolves versions permitted by the constraints and updates the lock file. That makes update a dependency-change operation rather than a routine deployment step. Without a lock file, install must resolve dependencies too.

For an application, I would review and test dependency updates before deploying the resulting lock file. The PHP version and extensions remain part of the environment contract; a lock file alone cannot supply a missing extension. Reproducibility also depends on controlled build scripts, plugins and artifacts, so dependency installation should be treated as code execution in the build process.

78. How should development dependencies be handled in deployment?

Development tools can be declared separately from runtime dependencies and omitted from a production installation when the application does not need them. The deployed artifact should still contain everything required to run, including any generated autoload metadata or build outputs. A mistaken dependency classification can make development work while production fails.

I would test the production-style installation and startup in CI rather than only run tests against a developer environment containing every package. Excluding development dependencies is not a complete security strategy: runtime packages still need review and patching. Secrets, test fixtures and unnecessary tools should also be kept out of the artifact through a deliberate build process.

79. How does dependency injection improve PHP tests?

Dependency injection makes collaborators explicit and allows a test to supply controlled implementations. It helps isolate business logic from time, networks, storage and other changing external systems. It is most useful when the abstraction represents a real boundary, not when every trivial operation is wrapped only to create mocks.

For an expiry rule, injecting a clock allows a test to evaluate an exact boundary without sleeping or changing the machine's clock. I would assert the business outcome rather than every internal method call. Excessive mocking can make tests reproduce the implementation and miss integration failures, so isolated tests should be complemented by focused tests of important real boundaries.

80. When should a PHP database test use a real database rather than a mock?

Use the real database engine when the behavior under test depends on SQL semantics, constraints, transactions, locking, encoding or driver behavior. A mock can confirm that application code calls an interface, but it cannot establish that a query is valid or a concurrency invariant holds.

An in-memory SQLite test can be useful for a SQLite application, yet it is not a complete substitute for PostgreSQL or MySQL behavior. I would use controlled fixtures and an isolated database matching the deployed engine for critical integration tests. Keep those tests focused so they verify meaningful boundaries without turning every small unit test into an expensive environment setup.

PHP Interview Questions and Answers for Experienced

These answers focus on failure modes and trade-offs. Look for bounded resource use, explicit uncertainty, recoverable state transitions and tests that match the actual deployment environment.

81. How would you diagnose a slow PHP endpoint before changing code?

I would separate queueing, PHP execution, database time, external calls and response transfer using request-level measurements. A slow endpoint does not necessarily spend most of its time executing PHP instructions. Tail latency and differences between successful and failing requests often reveal more than an overall average.

I would reproduce the relevant workload, inspect query counts and timings, and profile a representative request without exposing sensitive data. If workers are waiting on a remote service, changing a loop may have little effect. The improvement should be measured against the same scenario and checked for correctness, rather than inferred from a microbenchmark unrelated to the production bottleneck.

  • Separate time waiting for a worker from time executing the request.

  • Measure database and outbound calls, including repeated queries.

  • Profile the relevant code path and compare tail latency under realistic load.

  • Retest the same behavior after the change, including error paths.

82. What does OPcache optimize, and what does it not cache?

OPcache stores compiled PHP bytecode so requests can avoid repeatedly parsing and compiling unchanged source. It does not automatically cache database results, HTTP responses or arbitrary application values. Its configuration and deployment invalidation behavior therefore affect startup and code freshness rather than every category of application performance.

I would monitor cache capacity and relevant statistics and choose a deployment strategy that reliably activates the intended release. Disabling timestamp validation without a corresponding invalidation or restart process can leave old code running. A warm opcode cache can improve execution overhead while the application remains slow because of queries, remote calls or an exhausted FPM worker pool.

83. When might PHP's JIT help, and why should it be benchmarked?

JIT compilation can improve some CPU-intensive workloads by compiling suitable operations into machine code. It is not a guarantee that ordinary request-handling applications become materially faster, especially when they spend most time waiting on databases or networks. Its configuration and behavior also depend on the PHP release and environment.

I would benchmark a representative workload with realistic warm-up, concurrency and memory constraints, then compare both latency and resource use. A numerical loop benchmark can demonstrate a narrow benefit without predicting a full application's performance. Operational complexity and debugging requirements also belong in the decision rather than enabling a feature solely because it sounds faster.

84. How does preloading differ from ordinary OPcache behavior?

Preloading loads selected PHP code when the server starts so specified definitions can remain available across requests in that process environment. It can reduce repeated initialization work, but it changes how code is activated and updated. It is not simply a switch that safely loads every application file.

I would select preload candidates carefully, avoid request-specific work and test the deployment lifecycle. Code changes may require restarting the relevant workers or service to replace preloaded definitions. The benefit depends on the application's structure, and a preload script that assumes request context or unavailable dependencies can turn a performance experiment into a startup failure.

85. How would you choose an FPM worker count?

I would consider memory per worker, CPU availability, request duration, downstream connection capacity and the acceptable queueing behavior. Increasing workers can improve concurrency only while the host and dependencies can support it. Too many workers can cause memory pressure or overload a database without increasing useful throughput.

I would measure representative peak memory and observe queue length, active workers and latency under load, with headroom for the operating system and other services. The pool's process-management mode and timeouts also matter. A formula based only on total RAM divided by one idle worker's memory is insufficient when real requests have variable memory and external-resource demands.

Constraint

What to measure

Failure if ignored

Memory

Representative peak worker usage and host headroom

Swapping or process termination

Downstream capacity

Database and remote-service concurrency

Connection exhaustion or overload

Queueing

Busy workers, queue depth and tail latency

Timeouts despite low average latency

CPU

Utilization under actual request mix

More workers competing for the same compute

86. Why can persistent database connections be risky in a worker pool?

Persistent connections can reduce connection setup overhead, but a pool of PHP workers can hold many connections and potentially retain session-level database state. Transactions, temporary settings and other state need deliberate cleanup and driver-specific understanding. Persistence is not the same as a single shared application-wide connection.

I would budget connections across all replicas and workers, then test recovery after network failure or database restart. The application should not assume a reused connection is healthy or in the desired state merely because connection creation returned quickly. For some workloads, simpler short-lived connections or a suitable external pool provide a better operational trade-off.

87. What changes when PHP code runs in a long-lived worker instead of a fresh request lifecycle?

Application state can survive between jobs or requests, including static properties, service instances, caches and captured references. Code that was harmless when the process ended after each request can leak memory or user-specific state in a long-lived environment. The runtime's reset mechanisms must be understood rather than assumed.

I would separate immutable shared services from per-job state, clean up resources and test multiple different jobs through the same process. A test that starts a new process for each case can miss cross-job contamination. Worker recycling can limit damage, but it should complement explicit state management rather than conceal a persistent correctness or memory problem.

88. How would you investigate growing memory use in a PHP worker?

I would distinguish live retained data from allocator behavior and temporary peaks, then observe memory over repeated representative jobs. Common causes include unbounded caches, listeners, static collections, closures retaining objects and large result sets. Garbage collection cannot reclaim objects that remain reachable by design.

I would compare a baseline with a controlled workload and inspect what survives each job. Releasing references, closing resources and bounding collections should address the cause. Forcing collection or restarting frequently may reduce symptoms without explaining them. The fix should be checked for both steady-state memory and correctness across repeated work, not just one successful execution.

89. What do fibers provide, and what do they not provide automatically?

Fibers provide suspendable execution contexts with their own call stacks. They allow a scheduler or asynchronous library to pause and resume work while keeping code relatively sequential in appearance. They do not automatically make blocking I/O nonblocking or run CPU-bound PHP code in parallel.

I would use them through a runtime whose scheduling and I/O behavior are understood. A blocking database call can still stall the relevant execution thread even when invoked inside a fiber. Cancellation, deadlines and resource cleanup remain design concerns, so fibers should not be described as a drop-in solution for every concurrency or performance problem.

90. How would you prevent an asynchronous PHP service from creating unbounded work?

I would set limits on concurrent operations, queued tasks, response sizes and total request deadlines. Concurrency can reduce waiting time, but issuing every possible operation at once can exhaust sockets, memory or downstream capacity. Backpressure should propagate when the system cannot safely accept more work.

For an endpoint fetching many remote records, I would use bounded concurrency and define partial-failure behavior. Timeouts must account for both queueing and execution, and cancellation should release resources where supported. A fast happy-path demonstration is not evidence that the design survives slow dependencies or a burst of large requests.

91. How would you make a queue consumer safe when a job can be delivered more than once?

I would assume redelivery is possible and design the business effect to be idempotent or explicitly deduplicated. The deduplication record and state change need an appropriate atomic relationship, typically within the same durable system. Merely checking a flag before acting can race with another worker.

For a payment-related command, a unique operation key can identify the intended effect, with conflicts handled consistently. Acknowledgment should follow the required durable outcome, while retries need bounded backoff and a path for poison messages. Exactly-once wording is not a substitute for explaining what happens if the worker crashes after committing but before acknowledging the job.

92. Why is an outbox useful when a PHP transaction must publish an event?

An outbox records the application state change and an event-to-be-published in the same database transaction. A separate process publishes pending events and marks progress. This closes the gap where the database commits but the process crashes before notifying another service.

The publisher can still send an event more than once if it crashes after sending but before recording completion, so consumers must handle duplicates. I would define event identity, ordering requirements, retry policy and retention. The pattern provides a recoverable handoff; it does not turn the database and message broker into one magically atomic transaction.

93. How should a PHP API implement an idempotency key for a state-changing request?

The server should associate a scoped key with the request's semantic payload and a durable result or processing state. A repeated equivalent request can then retrieve the established outcome, while reuse with different input should be rejected according to the API contract. The check and reservation must resist concurrent requests.

I would define key scope, retention, in-progress behavior and failure recovery. Recording a key only after the side effect leaves a crash window, while recording it before work without recovery can leave operations stuck forever. External providers may offer their own idempotency keys, but the application still needs to coordinate its internal state and avoid treating a timeout as proof that nothing happened.

94. How would you handle deadlocks without retrying unsafe work?

I would identify the database's specific transient deadlock or serialization failure and retry the appropriate transaction boundary with a bounded policy. The transaction should be reconstructible from stable inputs. External side effects must not be repeated blindly as part of a database retry.

I would also investigate lock order, transaction duration and access patterns rather than rely on retries alone. A consistent locking order can reduce avoidable deadlocks, though it does not eliminate every conflict. Tests should exercise the target engine's behavior, and logging should distinguish a recovered retry from a persistent failure that requires operational attention.

95. Why can PHP sessions serialize otherwise independent requests?

Some session handlers, including common file-based behavior, lock session data while a request has it open. A second request using the same session can wait even if it performs unrelated application work. This can make a slow background request delay page actions for that user.

I would keep the session's writable period short and close it after required changes, using the appropriate session API and handler behavior. After closing, later changes to the in-memory session array are not automatically persisted. The fix must preserve correct state updates; disabling locking without another concurrency strategy can replace slow requests with lost or inconsistent session data.

96. How would you design logout and session revocation across several devices?

I would distinguish ending the current browser session from invalidating all active sessions or credentials for the account. Clearing a cookie affects that browser's presentation, while server-side state determines whether an existing credential remains valid. A multi-device policy needs a durable way to identify and revoke the relevant sessions.

I would consider password changes, account compromise, privilege changes and concurrent requests, with explicit expiry and revocation checks. Stateless tokens require a different revocation strategy from a central session store. The user interface should accurately describe whether the action signs out this device or all devices, rather than promise broader invalidation than the backend implements.

97. Why should untrusted data not be passed to unserialize()?

PHP unserialization can instantiate objects and invoke behavior through autoloading and magic methods. That makes it unsuitable as a generic parser for untrusted data, even when an allowed-classes option is supplied. The official guidance explicitly warns against treating that option as sufficient protection for hostile input.

For external interchange, I would use a format such as JSON with schema and domain validation. Existing stored serialized data also needs integrity and provenance controls, plus a migration plan where appropriate. A signature can establish that data came from an authorized writer if implemented correctly, but it does not make arbitrary object restoration a simple or universally safe data boundary.

98. How should a webhook signature be verified in PHP?

Verify the provider's specified signature over the exact bytes and metadata required by its protocol, using a trusted secret and a timing-safe comparison where appropriate. Decoding and re-encoding JSON before verification can change whitespace or key order and invalidate a signature. The raw request body must therefore be preserved for verification.

I would also enforce the provider's timestamp or replay rules and make event processing idempotent. A valid signature establishes the message's authenticated origin under that scheme, not that it has never been processed or that every requested action is authorized internally. Secrets and raw sensitive payloads should not be written into diagnostic logs during troubleshooting.

99. How should a PHP service compare secrets or authentication tokens?

Use an appropriate constant-time comparison function such as hash_equals() for a comparison of expected and supplied secret-derived strings, with the trusted value in the expected position. Ordinary equality can have timing behavior unsuitable for that security boundary. Input type and format should be checked before comparison.

This is only one part of verification. The token must also be unpredictable, correctly scoped, unexpired and protected in storage and transport. I would not replace a complete cryptographic verification API with a hand-built comparison when a vetted API already implements the required scheme. Timing-safe comparison does not compensate for a weak token or a leaked secret.

100. How would you stream a large response without loading it all into memory?

I would ensure the entire path is incremental: source reading, transformation, encoding and output. A generator does little if a database driver buffers all rows or the response layer collects every chunk before sending. Web-server, proxy and compression buffering can also affect when clients receive bytes.

For a large export, I would control batch size, escape the chosen format correctly and define behavior if the client disconnects or an error occurs after headers are sent. Streaming reduces memory only when intermediate stages remain bounded. It also changes error handling because a partially delivered response cannot always be replaced with a clean JSON error document.

101. What causes headers already sent errors, and how should they be fixed?

Headers and cookies must be established before response output has been committed under the runtime's buffering behavior. Unexpected output can come from whitespace, a byte-order mark, debugging statements or an included file. The reported file and line often help locate the first output.

I would remove unintended output and establish clear ownership of response construction. Output buffering can be useful deliberately, but enabling it merely to conceal an architectural problem can make behavior depend on buffer thresholds. Redirects should also terminate or return through the intended control flow so the application does not continue performing work after deciding to send a different response.

102. How would you plan a PHP version upgrade safely?

I would inventory the application's syntax, dependencies, extensions and deployment configuration, then read migration guidance for every relevant version transition. A successful dependency resolution does not prove that runtime behavior is compatible. Deprecations should be investigated before they become harder failures in a later release.

I would test critical workflows and production-like configuration on the target version, compare observability and performance, and define a rollback path compatible with any data changes. Version-specific features should only enter shared code after the minimum supported runtime changes deliberately. The current support table informs urgency, but it does not replace application-specific compatibility evidence.

  • Read migration changes for the complete upgrade path.

  • Check dependencies, extensions and the actual web-worker configuration.

  • Exercise critical workflows, deprecations and performance on the target version.

  • Define rollout, monitoring and rollback boundaries before deployment.

103. How should a library declare and test its supported PHP versions?

Declare the supported PHP constraint and required extensions in Composer metadata, then test the meaningful supported combinations in CI. The lowest supported version matters because code can accidentally use newer syntax or APIs while passing tests on the developer's machine. Dependency versions can also narrow the effective support range.

I would distinguish the library's public promise from the versions used by one application consuming it. Static analysis and platform configuration can help, but they do not reproduce every runtime or extension behavior. Dropping an older version should be an intentional compatibility decision with release communication, not an accidental consequence of adopting a convenient language feature.

104. Why should PHP version and extension checks happen in the deployment environment?

The CLI, FPM pool and build environment can use different binaries, configuration files and extensions. A command that works in a developer terminal does not establish that the web request runtime has the same capabilities. Configuration values and loaded extensions can also differ between pools or containers.

I would inspect the actual deployment runtime through approved diagnostics and verify required platform packages during the build and release process. Publicly exposing a full phpinfo page is unnecessary and can disclose sensitive configuration. The goal is reproducible, controlled evidence of the environment, followed by a startup check that fails clearly when a required capability is absent.

105. How should environment configuration and secrets be handled in PHP?

Configuration should be explicit, validated at startup and separated from source code where it varies by environment. Secrets should come from approved secret-management or deployment mechanisms with limited access and rotation procedures. Reading an environment variable does not by itself make a secret secure.

I would prevent credentials from appearing in exceptions, logs, debug pages or committed fixtures. Missing mandatory configuration should fail clearly rather than silently select an unsafe default. Long-lived workers may need a defined restart or reload process after rotation, so changing the secret in a central store is not enough if processes continue using an old cached value.

106. How would you make a PHP deployment compatible with a rolling database migration?

I would plan for old and new application versions to run simultaneously and keep the database changes compatible during that period. An expand-and-contract approach can add new structures first, transition reads and writes, backfill safely and remove obsolete structures only after old code is gone.

A rename or new non-null constraint can break still-running workers even when the new release works in isolation. I would examine queued jobs and long-lived processes as well as web instances, and separate reversible code rollback from irreversible data changes. The deployment plan should state how progress is monitored and when it is safe to perform the final cleanup.

107. How would you assess whether a cache improves a PHP application correctly?

I would define the cached value, key, ownership, freshness requirement and invalidation strategy before measuring speed. A cache can return a fast but incorrect result if it omits tenant, permissions, locale or relevant inputs from the key. Correctness under updates matters as much as hit rate.

I would test misses, expiry, concurrent recomputation and dependency failure. Stampede protection and bounded storage may be necessary, but the policy should match the cost of stale data. An authorization-sensitive response requires special care: a cached result must not allow one user's permissions or private data to bleed into another request.

108. What makes a cache stampede different from an ordinary cache miss?

A stampede occurs when many requests miss or expire the same expensive item and recompute it concurrently. The resulting load can overwhelm the database or service the cache was intended to protect. A high average hit rate can hide this sharp failure mode.

Depending on the freshness contract, I would consider request coalescing, short-lived locks, staggered expiry or serving a bounded stale value while one worker refreshes it. Lock expiry and failed refreshes need explicit handling so the remedy does not create a permanent outage. The application should also remain correct when the cache is unavailable rather than assume it is a durable source of truth.

109. How should logs and traces support PHP incident investigation without leaking data?

Record the operation, relevant identifiers, timing and failure category so requests can be correlated across components. Avoid logging credentials, session tokens or entire sensitive payloads by default. Structured fields help investigation when their meaning and retention are controlled.

I would propagate a safe correlation identifier and distinguish expected validation failures from unexpected exceptions. Logs need access controls and protection against untrusted text disrupting their format. Observability should answer where time or failure occurred, not require reproducing every user's private input in a searchable system. Sampling and redaction also need testing so they do not remove the evidence essential to a critical workflow.

110. How would you choose between exceptions and explicit result objects for a domain operation?

I would consider whether failure is expected, how callers should respond and whether the type system can express the alternatives clearly. Exceptions can propagate exceptional failures to a suitable boundary, while explicit results can make routine outcomes such as a declined application visible in the normal control flow.

Neither approach is inherently correct for every layer. A result object should not allow callers to ignore failure accidentally, and an exception should not turn every ordinary business branch into hidden control flow. I would keep infrastructure details out of the public domain contract and use consistent conventions so a caller can tell which outcomes must be handled locally.

111. How can static analysis complement PHP runtime tests?

Static analysis can detect incompatible types, unreachable paths and unsafe assumptions without executing each input combination. It is especially useful for array shapes, generics expressed through tool annotations and contracts beyond native declarations. Its findings depend on the accuracy of the code model and configuration.

Runtime tests verify actual behavior, including integration with extensions, databases and external boundaries. I would use both, and investigate suppressions rather than accumulate them indiscriminately. A clean analysis report does not prove business correctness or production compatibility, while passing tests do not establish that unexercised paths respect every contract.

112. How should a team decide whether to adopt PHP 8.4 property hooks in an existing API?

I would consider the minimum runtime, tooling support, property semantics and impact on consumers before replacing explicit access methods. Hooks can preserve property syntax while adding controlled logic, but changing a plain property into computed or effectful access can alter expectations about cost and behavior.

I would prefer small deterministic operations and test serialization, reflection and framework integration where those depend on property metadata. Readonly compatibility and visibility rules also need review. The migration should serve a clearer API or invariant, not simply introduce new syntax across the codebase without considering libraries or deployment environments that still require older PHP releases.

113. What does the PHP 8.5 pipe operator do, and when is it useful?

The PHP 8.5 pipe operator passes the result on its left into a callable on its right, allowing a sequence of transformations to be read from left to right. It can improve clarity for a small pipeline of compatible unary operations. It does not automatically handle errors, validate intermediate values or make operations asynchronous.

I would use it when the transformations remain easy to name and the project's minimum runtime is PHP 8.5. A deeply conditional workflow may be clearer with ordinary variables and control flow. Code intended for older supported runtimes must avoid the syntax, since a runtime version check inside the same file cannot rescue syntax that an older parser cannot understand.

PHP 8.5+ — a small left-to-right transformation

<?php
$name = '  Alice  ' |> trim(...) |> strtoupper(...);
echo $name, "\n";
// Expected: ALICE. Requires a PHP 8.5 parser.
<?php
$name = '  Alice  ' |> trim(...) |> strtoupper(...);
echo $name, "\n";
// Expected: ALICE. Requires a PHP 8.5 parser.
<?php
$name = '  Alice  ' |> trim(...) |> strtoupper(...);
echo $name, "\n";
// Expected: ALICE. Requires a PHP 8.5 parser.

114. How would you review a PHP package before introducing it into a sensitive service?

I would assess its purpose, maintenance, provenance, dependency tree, licensing, security history and required privileges, then examine how it will be used at the application's boundary. Popularity or a clean advisory scan is useful evidence but not proof that the package is safe or suitable.

Composer plugins and scripts deserve particular attention because installation can execute code. I would pin the reviewed dependency set through the application's lock file, run relevant tests and define an update process. For a small requirement, the operational burden of a large dependency may outweigh its convenience; for cryptographic or protocol work, inventing a replacement can be substantially riskier than using a maintained specialist implementation.

115. How would you investigate an intermittent PHP bug caused by shared state?

I would reproduce multiple requests or jobs within the same relevant process lifecycle and vary their order, users and inputs. The investigation should examine static fields, singleton services, caches, closures and mutable collaborators. A bug that disappears when each test starts fresh may be revealing the actual lifecycle mismatch.

I would identify the state owner and reset boundary, then replace unintended sharing with per-operation state or immutable data. Adding a broad reset after every job can be a temporary safeguard, but it should not obscure dependencies that remain shared elsewhere. Regression coverage should include the sequence that caused contamination, not just the individual requests in isolation.

116. How would you design cancellation and cleanup for a PHP background job?

I would define safe interruption points, durable progress and which resources or external operations may remain in flight. A job should stop accepting new work when cancellation is requested and leave state that can be retried or inspected. Finally blocks and signal handlers help with some paths but cannot guarantee cleanup after every termination.

For a batch export, I would record completed units or produce a temporary artifact that becomes visible only when complete. Transactions should be short enough to release locks promptly, and external requests need deadlines. The recovery plan must account for a process being killed between any two durable operations, rather than assume graceful shutdown always has enough time to finish.

117. How should a PHP service handle a timeout after sending a payment request?

A timeout means the client did not obtain a definitive response; it does not prove the remote operation failed. I would preserve an operation identifier and reconcile with the provider using its supported status or idempotency mechanisms before creating a second independent payment. The local state should represent uncertainty explicitly.

Retries must follow the provider's contract and avoid changing the intended operation accidentally. I would also separate transport deadlines from the business workflow's recovery period. Returning a simple failure while silently abandoning reconciliation can leave customers charged without a corresponding internal record, while unconditional retry can create duplicate effects.

118. How would you refactor a legacy PHP script without rewriting everything at once?

I would first identify the behavior that must remain stable and establish focused characterization tests around meaningful inputs and outputs. Then I would extract clear boundaries, such as parsing, domain decisions and persistence, while keeping changes small enough to diagnose. The goal is improved control over behavior, not merely moving procedural code into classes.

I would address security or correctness defects explicitly rather than preserve them accidentally as unquestionable requirements. Side effects and globals deserve special attention because they can make extraction change execution order. A gradual migration with observable checkpoints often provides a safer route than a large rewrite whose equivalence is difficult to establish.

119. How should a PHP team handle a security patch that could change application behavior?

I would assess the exposure and urgency, review the official change and affected dependencies, and test the critical paths on the patched build. Security fixes can alter previously accepted behavior, so a rollback decision must consider reintroducing the vulnerability as well as restoring functionality.

I would use a controlled rollout and monitoring where appropriate, with a mitigation or forward-fix plan for compatibility problems. Version strings alone may not reveal vendor backports, so the actual distribution and patch evidence matter. The response should preserve a record of the risk decision and avoid leaving an unsupported runtime indefinitely because one workflow was not prepared for the update.

120. What would demonstrate senior PHP engineering judgment in an interview?

A senior candidate should connect language behavior to application correctness, security and operational constraints. They should explain data boundaries, failure modes and lifecycle assumptions, then choose a proportionate design. Knowing syntax matters, but identifying a race, an uncertain external outcome or a version-dependent assumption can matter more than recalling an obscure feature.

For a case involving a database write and remote payment, I would expect explicit reasoning about authorization, idempotency, timeouts, durable state and recovery. The candidate should also state what needs a real integration test and what a unit test can establish. Clear trade-offs and an honest verification plan are stronger evidence than claiming that a framework or language feature eliminates every risk.

PHP Documentation and Further Reading

These official language, tooling and interoperability sources support further study. Check the target PHP release, extension availability and database-driver documentation before applying an example. Security controls depend on the complete application and infrastructure; a short language example is not a production security audit.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts