Skip to content
Tutorials Center
My learning

Topics

Lesson 147 of 147 ยท Practice and Review

PHP Interview Questions

49 PHP interview questions with clear answers plus 5 code-reading puzzles, from types and arrays to OOP, enums, exceptions, security, OPcache and Composer.

PHP interviews test two things: whether you know how the language really behaves (how == compares a string with a number, when an array is copied, what static:: refers to, where a session actually lives) and whether you can explain the professional habits around it: strict types, prepared statements, escaped output, hashed passwords, Composer and tests. This page collects 49 questions that come up again and again for PHP and Laravel/Symfony roles, grouped by level and topic, with short, accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in two or three sentences, follow the link to its lesson and review it. Five more ask you to read code and predict its output: make your prediction first, then press Run.

Tip: a short correct answer with a tiny example beats a long recital. Mention the trap ("'abc' == 0 was true before PHP 8"), the safe habit ("I always pass true as the third argument of in_array") and the tool that catches the bug ("PHPStan flags that comparison"). That's what makes an answer sound like experience instead of memorization.

Junior level

Language basics

What is PHP, and where is it used today?

PHP is a general-purpose scripting language designed for the web. Code runs on the server: a web server hands each request to PHP, the script builds a response (usually HTML or JSON), and the browser only ever sees that output. PHP powers a large share of all websites, including WordPress, Wikipedia and many shops, and modern frameworks such as Laravel and Symfony. Since PHP 7 and 8 it is fast, has a strong type system, and also runs command-line tools, queue workers and long-running processes. See Getting Started with PHP and How PHP Works.

What is the difference between echo, print, print_r and var_dump?

echo and print are language constructs that output strings; echo accepts several comma-separated arguments and returns nothing, while print takes one argument and returns 1, so it can be used in expressions (rarely useful). print_r prints arrays and objects in a readable form, and var_dump adds the types and lengths, such as string(3) "abc" or bool(false), which makes it the better debugging tool, because print_r(false) prints nothing at all. var_export prints valid PHP code. See Output: echo, print, printf.

What is the difference between single and double quotes?

Single-quoted strings are literal: only \' and \\ are escapes, and $name stays as the text $name. Double-quoted strings interpolate variables ("Hi $name", "{$user->name}", "{$items['id']}") and understand escapes such as \n, \t and \u{1F600}. Heredoc (<<<TEXT) behaves like double quotes for multi-line text, and nowdoc (<<<'TEXT') like single quotes. Many style guides use single quotes unless interpolation or escapes are needed. See Strings.

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

=== (identical) is true only when both values have the same type and value. == (equal) first converts the operands to a common type, which is called type juggling: '1' == '01' and 100 == '1e2' are both true. PHP 8 made == saner: a number is compared with a non-numeric string as strings, so 0 == 'abc' is now false (it was true in PHP 7). Use === and !== by default, and use == only when you deliberately want conversion. The same applies to functions with a strict parameter, such as in_array($x, $list, true). See Comparison Operators.

What data types does PHP have?

Four scalar types: int, float, string and bool. Compound types: array (an ordered map), object (including closures and enums), callable and iterable. Special types: null and resource (for things like open files, partly replaced by objects in recent versions). For type declarations there are also mixed, void, never (PHP 8.1), static, self, nullable ?T, unions A|B, intersections A&B and DNF types (A&B)|null (PHP 8.2). gettype() and get_debug_type() (PHP 8.0) report a value's type. See Data Types.

What is the difference between isset, empty and is_null?

isset($x) is true when the variable (or array key, or property) exists and is not null; it never warns about undefined variables. empty($x) is true when the value is missing or falsy: '', '0', 0, 0.0, null, false or [], and the '0' case surprises many people. is_null($x) is a normal function that is true only for null, and it warns when the variable doesn't exist. To check whether an array key exists even when its value is null, use array_key_exists. See Variables and Booleans and null.

What is the difference between include, require, include_once and require_once?

All four load and run another PHP file. If the file is missing, include emits a warning and the script continues, while require stops with a fatal error, so require is the right choice for files the code can't work without. The _once variants remember which files were already loaded and skip them the second time, which prevents "cannot redeclare function" errors. In modern projects you rarely write these at all: Composer's autoloader loads classes on demand, and only the entry point does require __DIR__ . '/../vendor/autoload.php';. See Autoloading and Composer.

What is the difference between define and const?

Both create constants that can't be reassigned. const NAME = value; is resolved at compile time, works at the top level of a file and inside classes (class constants), and respects the current namespace. define('NAME', value) is a function call that runs at runtime, so it can be used inside if blocks or with a computed name, but not in a class body. Constants have no $, are global, and can hold scalars, arrays and, since PHP 8.1, enum cases and new expressions in some contexts. See Constants.

Arrays and strings

What kinds of arrays does PHP have?

Technically one: every PHP array is an ordered map from keys (int or string) to values. Used with automatic keys 0, 1, 2โ€ฆ it acts as a list (an indexed array); with string keys it acts as a dictionary (an associative array); arrays of arrays give multidimensional data. Keys are normalized: '5' becomes the integer 5, true becomes 1, and floats are truncated (with a deprecation since PHP 8.1 when precision is lost). array_is_list() (PHP 8.1) tells you whether an array has the keys 0 to n-1 in order. See Arrays and Associative Arrays.

What is the difference between array_merge and the + operator?

array_merge($a, $b) appends: integer keys are renumbered, and for string keys the later array wins. $a + $b is a union: it keeps everything from $a and only adds keys from $b that $a doesn't have, so for duplicate keys the left side wins and integer keys are never renumbered. Use + for "defaults that the user's values override" written as $userOptions + $defaults; use array_merge or the spread operator [...$a, ...$b] to combine lists. See Array Functions.

Why does strlen('hรฉllo') return 6?

PHP strings are sequences of bytes, and strlen counts bytes. In UTF-8, รฉ takes two bytes, so the five-character word is six bytes long. The mb_* functions work with characters instead: mb_strlen('hรฉllo') is 5, and mb_substr, mb_strtoupper, mb_str_pad (8.3) and mb_trim (8.4) are the safe choices for user-facing text. Byte functions like substr or strrev can cut a character in half and produce invalid UTF-8. See Unicode and Multibyte Strings.

What are the common ways to search in strings and arrays, and what is the classic strpos trap?

For strings, PHP 8 added str_contains, str_starts_with and str_ends_with, which return plain booleans. The older strpos returns the position or false, and position 0 is falsy, so if (strpos($text, 'Hello')) fails when the text starts with "Hello". Always compare with !== false. For arrays, in_array and array_search compare loosely unless you pass true as the third argument, and array_search has the same position-0 trap. See String Functions.

The web

What are superglobals?

Superglobals are built-in arrays available in every scope without global: $_GET (query-string parameters), $_POST (form fields of a POST request), $_FILES (uploads), $_COOKIE, $_SESSION (after session_start()), $_SERVER (request and server information such as REQUEST_METHOD and REQUEST_URI), $_ENV, $_REQUEST (a merge of GET, POST and cookies, best avoided) and $GLOBALS. Everything in $_GET, $_POST, $_COOKIE and most of $_SERVER comes from the client, so it must be validated before use and escaped on output. See Superglobals.

When do you use GET and when POST?

GET requests should be safe: they read data and can be bookmarked, cached, shared and repeated, like a search form or a page with filters. Their parameters appear in the URL, logs and browser history, so never put passwords or tokens there. POST requests change something (create an account, place an order, send a message); their data travels in the request body. After processing a POST form, answer with a redirect (the POST-redirect-GET pattern), so reloading the page doesn't submit it again. See Handling Forms.

What is the difference between cookies and sessions?

A cookie is a small piece of data stored in the browser and sent with every request to the site, so the user can read and change it. A session stores data on the server; the browser only holds a random session ID, usually in a PHPSESSID cookie. Use sessions for anything that must be trusted, such as the logged-in user's ID, and cookies for harmless preferences. Set session cookies with HttpOnly, Secure and SameSite=Lax, and call session_regenerate_id(true) after login to prevent session fixation. See Cookies and Sessions.

Code reading: comparisons and juggling

Predict every line before you run it. All results are for PHP 8.

PHP Predict the output: loose comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Explain the output.

It prints false, true, true, true, false, then int(2) and string(2) "11", then true. Since PHP 8, a number and a non-numeric string are compared as strings, so 0 == 'a' and 'abc' == 0 are false (both were true in PHP 7). A number and a numeric string, or two numeric strings, are compared as numbers, so '1' == '01' and 100 == '1e2' are true. null == false is true because both convert to false. + always does arithmetic and . always concatenates, so the operator decides the type. And '0' is one of the falsy values, so empty('0') is true. See Type Juggling and Casting.

Mid level

Functions and types

What does declare(strict_types=1) do?

It switches scalar type declarations in that file to strict mode. Without it, PHP coerces arguments: passing '5' to an int parameter silently gives 5. With it, PHP throws a TypeError instead; the only allowed conversion is int to float. The setting applies to calls made from the file that declares it (and to return values in that file), not to the functions defined there, and it must be the very first statement. It doesn't affect operators or comparisons. Most modern codebases put it at the top of every file. See Type Declarations.

How are arguments passed: by value or by reference?

By value, by default: the function gets its own copy of scalars and arrays, so changing them inside doesn't affect the caller. PHP makes this cheap with copy-on-write: the array is only really copied if the function modifies it. Objects are also passed by value, but the value is a handle to the object, so the function can change the object's properties, though assigning a new object to the parameter doesn't affect the caller. A parameter declared with & (function add(array &$list)) is passed by reference and changes the caller's variable. See Parameters and Arguments.

What are closures, and how do use and arrow functions differ?

A closure is an anonymous function stored in a variable or passed as an argument, for example to array_map or usort. A classic function () use ($rate) { ... } must list the outer variables it needs in use; they are captured by value when the closure is created, unless you write use (&$total) to capture by reference. An arrow function fn ($x) => $x * $rate (PHP 7.4) captures automatically by value, but its body is a single expression. PHP 8.1 added first-class callable syntax: strlen(...) or $object->method(...) creates a closure from an existing function. See Anonymous Functions and Closures.

What is the difference between switch and match?

match (PHP 8.0) is an expression that returns a value, compares with ===, has no fall-through, can list several values per arm (1, 2 => 'low'), and throws an UnhandledMatchError when no arm matches and there's no default. switch is a statement that compares with ==, falls through to the next case unless you write break, and silently does nothing when nothing matches. match (true) is a handy pattern for ranges of conditions. Prefer match for mapping values; switch is still fine when each case runs several statements. See switch and match.

What do ??, ?: and ?-> do?

$a ?? $b (null coalescing) returns $a if it exists and isn't null, otherwise $b, without warnings for missing variables or keys, so $_GET['page'] ?? 1 is the standard way to read optional input. ??= assigns only when the left side is null. $a ?: $b (the short ternary) returns $a if it is truthy, so 0 and '' also fall back to $b. $user?->getAddress()?->city (nullsafe, PHP 8.0) stops and returns null as soon as one link of the chain is null. Nested ternaries without parentheses are a compile error since PHP 8.0. See Null Coalescing, Ternary and Nullsafe Operators.

Object-oriented PHP

What is the difference between an abstract class and an interface?

An interface is a pure contract: method signatures and constants (and, since PHP 8.4, property declarations), with no state. A class can implement any number of interfaces. An abstract class can mix abstract methods with real methods, properties and a constructor, but a class can extend only one parent. Use an interface to describe a capability that unrelated classes share (Countable, JsonSerializable, a PaymentGateway), and an abstract class to share implementation between closely related classes. Code should usually depend on interfaces, which keeps it easy to test and swap implementations. See Abstract Classes and Interfaces.

What are traits, and when should you avoid them?

A trait is a bundle of methods (and properties, constants since PHP 8.2, and abstract or static members) that is copied into a class with use TraitName;. It gives code reuse without inheritance, which helps because PHP has single inheritance. Conflicts between two traits are resolved with insteadof and as. Traits are good for small, self-contained behaviors such as timestamps or a toArray helper. Avoid them as a dumping ground: a trait can't be type-hinted, hides dependencies, and can rely on properties of the class that uses it. Often composition (injecting a collaborator) is clearer. See Traits.

What is the difference between self, static and parent?

self:: refers to the class where the code is written. static:: refers to the class that was actually called at runtime, which is called late static binding. parent:: refers to the parent class, typically to call an overridden method or constructor. The difference matters in inherited static methods: a create() method defined in Model that returns new static() creates a User when called as User::create(), while new self() always creates a Model. The code-reading question below shows it. See Static Properties and Methods.

What do public, protected and private mean?

They control where a property, method or constant can be used. public members are accessible everywhere, protected ones in the class and its subclasses, and private ones only in the class that declares them. PHP 8.4 added asymmetric visibility: public private(set) int $balance can be read everywhere but written only inside the class, and public protected(set) lets subclasses write too. Good design keeps state private and exposes behavior through methods, so the class can guarantee its rules. See Classes, Properties and Methods and Property Hooks and Asymmetric Visibility.

What are readonly properties and classes?

A readonly property (PHP 8.1) can be initialized once, from inside the class, and never changed afterward; writing it again throws an Error. It must have a type. A readonly class (PHP 8.2) makes every property readonly. Together with constructor promotion they make value objects short: final readonly class Money { public function __construct(public int $cents, public string $currency) {} }. To "change" a value object you return a new instance (a wither). Inside such a wither, PHP 8.5's clone($this, ['cents' => 500]) creates the modified copy in one step. Note that readonly is shallow: an object stored in a readonly property can still change internally. See Readonly Properties and Immutable Objects.

What are enums, and what is the difference between pure and backed enums?

Enums (PHP 8.1) define a type with a fixed set of possible values, such as enum Suit { case Hearts; case Spades; }. Each case is a singleton object, so === works and type declarations like function play(Suit $suit) reject anything else. A pure enum has only names; a backed enum gives each case a scalar value (enum Status: string { case Paid = 'paid'; }) for storing in databases or JSON, with Status::from('paid') (throws on unknown values) and tryFrom() (returns null). Enums can have methods, constants and implement interfaces, and cases() lists all cases. See Class Constants and Enums.

What are magic methods? Name a few.

Magic methods start with two underscores and are called by PHP automatically. __construct and __destruct run on creation and destruction; __toString converts an object to a string; __get, __set, __isset and __unset handle inaccessible properties; __call and __callStatic handle unknown methods; __invoke makes an object callable; __clone adjusts a copy after clone; __serialize and __unserialize control serialization. They are powerful (ORMs and proxies rely on them), but overusing __get and __call hides the real API from readers, IDEs and static analysis. See Magic Methods.

What happens when you assign an object to another variable, and what does clone do?

Assignment copies the handle, not the object: after $b = $a, both variables point to the same object, and a change through one is visible through the other. clone $a creates a new object with copies of the properties. The copy is shallow: properties that hold other objects still point to the same inner objects, unless __clone() clones them too. == on objects compares class and property values, while === is true only for the very same instance. See Comparing, Copying and Serializing Objects.

Errors and exceptions

What is the difference between Error and Exception?

Both implement the Throwable interface, so both can be thrown and caught. Exception and its subclasses (RuntimeException, InvalidArgumentException, JsonException, your own classes) represent conditions that the application may handle. Error and its subclasses (TypeError, ValueError, ArgumentCountError, DivisionByZeroError, UnhandledMatchError) are thrown by the engine for programming mistakes. Catch Exception subclasses where you can do something useful, and let Errors reach a global handler that logs them. catch (Throwable $e) belongs only in top-level handlers. See Exceptions.

How do warnings and notices differ from exceptions, and how should production be configured?

Warnings, notices and deprecations are diagnostics: PHP reports them and keeps running, for example "Undefined array key". Exceptions interrupt the normal flow until something catches them. Many frameworks convert warnings into ErrorException with set_error_handler, so every problem becomes visible. In production set display_errors=Off (never show internals to users) and log_errors=On with error_reporting=E_ALL, so everything is recorded in the logs. During development show everything. Avoid the @ operator, which hides the diagnostic but not the problem. See Errors, Warnings and Notices.

Databases and security

How do you prevent SQL injection?

Never build SQL by concatenating input. Use prepared statements with placeholders: $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$email]);. The SQL text and the values travel separately, so a value can never change the query's structure. Identifiers such as column names for ORDER BY can't be bound, so check them against a whitelist. Configure PDO with PDO::ERRMODE_EXCEPTION. Escaping functions and "magic quotes" are not a substitute. See Prepared Statements and SQL Injection.

What is XSS, and how do you prevent it in PHP?

Cross-site scripting happens when user-controlled text is output as HTML, so an attacker's <script> runs in other users' browsers with their session. The fix is to escape on output, in the right context: htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') for HTML text and quoted attributes (the flags are the default since PHP 8.1), rawurlencode for URL parts, json_encode with the JSON_HEX_* flags for data inside scripts. Template engines like Blade and Twig escape automatically. A Content-Security-Policy header adds a second layer of defense. See Preventing XSS.

What is CSRF, and how do you prevent it?

Cross-site request forgery tricks a logged-in user's browser into sending a request to your site from another site, for example a hidden form that posts to /account/delete; the browser attaches the session cookie automatically. Protect every state-changing request with a CSRF token: a random value (bin2hex(random_bytes(32))) stored in the session and included in each form, compared with hash_equals on submit. SameSite=Lax or Strict session cookies add a strong second layer, and state changes must never happen on GET. See Preventing CSRF.

How should passwords be stored?

With password_hash($password, PASSWORD_DEFAULT) and checked with password_verify($password, $hash). The default algorithm is bcrypt (cost 12 since PHP 8.4); Argon2id is available as PASSWORD_ARGON2ID when PHP is built with it. Both are deliberately slow and add a random salt, which is stored inside the hash string. After a successful login, call password_needs_rehash to upgrade old hashes. Never use md5, sha1 or plain hash() for passwords: they are designed to be fast, which makes brute force cheap. Store the hash in a column of at least 255 characters. See Password Hashing.

Code reading: foreach by reference and late static binding

The first program loops over the same array twice. Predict the output.

PHP Predict the output: foreach by reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Why does it print a,b,b?

After the first loop, $letter is still a reference to the last element, $letters[2]. The second loop assigns each element to $letter, which writes through the reference into $letters[2]: it becomes 'a', then 'b', and in the last step it is assigned to itself, so it stays 'b'. The fix is unset($letter); right after a by-reference loop, or avoiding references and using array_map or the key: foreach ($letters as $i => $letter) { $letters[$i] = ...; }. See foreach Loops.

The second program creates objects through inherited static methods.

PHP Predict the output: self vs static

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Explain why the two calls create different classes.

It prints User Model. Both methods are written in Model, but static is resolved at runtime to the class used in the call, User, while self always means Model, the class where the code is written. The static return type (PHP 8.0) tells callers and static analysers that User::create() returns a User. Named constructors and fluent builders in frameworks rely on this.

Senior level

How PHP runs

What happens between an HTTP request and a PHP response?

The web server (nginx, Apache, Caddy) receives the request and passes it to PHP, usually to PHP-FPM over FastCGI. FPM keeps a pool of worker processes; one of them runs the entry script, typically public/index.php. PHP compiles the scripts to opcodes (or takes them from OPcache), executes them, and the output plus headers go back to the web server. After the response, everything the request created is freed: PHP has a shared-nothing architecture, so each request starts clean and nothing leaks between users, but anything you want to keep must go into a database, cache or session store. See How PHP Works.

What do OPcache, preloading and the JIT do?

OPcache stores compiled opcodes in shared memory, so PHP doesn't parse and compile every file on every request; it's essential in production (with opcache.validate_timestamps=0 and a cache reset on deploy). Preloading (PHP 7.4) loads chosen files into memory once when the server starts, so their classes are always available. The JIT (PHP 8.0) compiles hot opcodes to machine code; it speeds up CPU-heavy work such as math or image processing, but typical web requests mostly wait for databases and I/O, so its gains there are small. Measure before tuning. See Performance and OPcache.

How does PHP manage memory?

Values live in reference-counted containers. When a variable is assigned to another, both share the same value and the counter goes up; arrays and strings are copied only when one side modifies them (copy-on-write). When the count drops to zero, memory is freed immediately. Reference counting alone can't free cycles (two objects pointing at each other), so a cycle collector runs periodically, and gc_collect_cycles() forces it. Within one web request this rarely matters, but long-running workers must avoid growing static caches and should watch memory_get_usage(). WeakMap (PHP 8.0) caches data per object without keeping it alive. See Performance and OPcache.

What are generators, and when do they help?

A function containing yield returns a Generator that produces values lazily: the function runs until the next yield, pauses, and continues when the caller asks for the next value. This keeps memory flat when you process large data, such as reading a multi-gigabyte log line by line or streaming database rows, because only one item exists at a time instead of a full array. Generators can yield keys, delegate with yield from, receive values with send() and return a final value with getReturn(). See Generators.

What are fibers, and how do they relate to async PHP?

A Fiber (PHP 8.1) is a block of code with its own call stack that can suspend itself from anywhere inside nested function calls with Fiber::suspend() and be resumed later with resume(). Fibers don't run in parallel; they let a scheduler switch between tasks while each one waits for I/O. Libraries such as Revolt, AMPHP and ReactPHP build event loops on them, so async code can look like normal synchronous code without yield or promise chains everywhere. Application code rarely uses fibers directly. See Fibers and Asynchronous PHP.

Architecture and ecosystem

What do Composer and PSR-4 autoloading do?

Composer is PHP's dependency manager. composer.json lists required packages with version constraints ("monolog/monolog": "^3.0"), composer install installs the exact versions recorded in composer.lock (commit the lock file for applications), and vendor/autoload.php registers an autoloader. PSR-4 maps namespace prefixes to folders, so App\Http\Controller is loaded from src/Http/Controller.php the first time it's used; no require statements needed. In production, run composer install --no-dev --optimize-autoloader. See Autoloading and Composer.

What are PSRs? Name the important ones.

PSRs are PHP Standard Recommendations from the PHP-FIG group, so that frameworks and libraries can work together. The most cited: PSR-1 and PSR-12 (coding style, now continued as the PER Coding Style), PSR-4 (autoloading), PSR-3 (logger interface), PSR-7 (HTTP message interfaces), PSR-11 (container interface), PSR-14 (event dispatcher), PSR-15 (HTTP middleware), PSR-17 (HTTP factories) and PSR-18 (HTTP client). Depending on these interfaces instead of concrete libraries keeps code portable. See Coding Standards and PSRs.

What is dependency injection, and what does a container do?

Dependency injection means a class receives its collaborators (usually through the constructor) instead of creating them or fetching them from globals: __construct(private Mailer $mailer) instead of new SmtpMailer() inside the class. This makes dependencies visible and lets tests pass fakes. A DI container builds these object graphs for you: it reads constructor type declarations with Reflection (autowiring), creates the dependencies recursively, and shares single instances where configured. Laravel's service container and Symfony's DependencyInjection component are examples. See OOP Design Principles and Reflection.

Explain the SOLID principles briefly with PHP in mind.

Single responsibility: a class has one reason to change (a UserRepository stores users; it doesn't send emails). Open/closed: add behavior by adding classes, for example a new Discount implementation, rather than editing a growing switch. Liskov substitution: a subclass must work everywhere its parent does, without stricter preconditions or surprising exceptions. Interface segregation: prefer small interfaces (Readable, Writable) over one huge one. Dependency inversion: high-level code depends on interfaces (PaymentGateway), and the concrete class is injected. Apply them pragmatically, not as ceremony. See OOP Design Principles.

What are covariance and contravariance in PHP?

They define how a child class may change a method's types while staying compatible with its parent. Return types are covariant: the child may return a narrower type (the parent returns Animal, the child Dog), because callers still get an Animal. Parameter types are contravariant: the child may accept a wider type (the parent accepts Dog, the child Animal), because it still handles everything the parent did. Property types are invariant. PHP enforces these rules when the class is declared, which is the Liskov principle checked by the engine. See The PHP Type System in Depth.

How do you test and statically analyze PHP code?

Unit and feature tests are written with PHPUnit or Pest (built on PHPUnit): arrange, act, assert, with test doubles for slow or external collaborators, and database tests often run on SQLite in memory or in transactions. Static analysis with PHPStan or Psalm reads the code without running it and finds type errors, impossible conditions, undefined methods and wrong generics described in PHPDoc (@param list<User>, @template T). A coding-style fixer (PHP-CS-Fixer, Laravel Pint, PHP_CodeSniffer) keeps formatting consistent. In CI, all three run on every pull request. See Testing PHP Code.

Why is unserialize on user input dangerous?

unserialize can create objects of any loaded class and restores their properties, and their magic methods (__wakeup, __unserialize, __destruct, __toString) then run with attacker-chosen data. Chains of such methods in common libraries ("gadget chains") can lead to file deletion or remote code execution. Never unserialize untrusted data: use json_decode for data exchange, or at least unserialize($data, ['allowed_classes' => false]), and sign data you must round-trip with hash_hmac. The same caution applies to phar:// paths on user-controlled file names. See Secure Coding Checklist.

How would you find and fix a slow PHP page?

Measure first. Check the database: log queries per request and look for N+1 patterns (one query per item in a loop), missing indexes and unbounded result sets. Then profile the code with a profiler such as Xdebug's profiler, Blackfire or SPX, or time sections with hrtime(true). Typical fixes: eager-load related rows, add indexes, paginate, cache expensive results (Redis, APCu, HTTP caching), move slow work such as email and image processing to a queue, and make sure OPcache is on. Verify each change with the same measurement. See Performance and OPcache and Pagination, Search and Database Patterns.

What are the most important features added in PHP 8.0 to 8.5?

8.0: named arguments, union types, match, nullsafe ?->, constructor promotion, attributes, str_contains, the JIT and saner string-number comparison. 8.1: enums, readonly properties, fibers, never, first-class callables, new in initializers, array_is_list. 8.2: readonly classes, DNF types, true/false/null as standalone types, Random\Randomizer, constants in traits. 8.3: typed class constants, #[\Override], json_validate, mb_str_pad. 8.4: property hooks, asymmetric visibility, new without parentheses, array_find/array_any/array_all, #[\Deprecated], Dom\HTMLDocument. 8.5: the pipe operator |>, clone with property changes, #[\NoDiscard], array_first/array_last and the URI extension. See What's New in PHP 8.0 to 8.5.

How do you deploy a PHP application safely?

Build a release from version control: composer install --no-dev --optimize-autoloader, compile front-end assets, and run tests in CI first. Configure production PHP with display_errors=Off, log_errors=On, expose_php=Off, OPcache on with timestamp validation off, and secrets in environment variables, never in the repository. Deploy to a new release folder and switch a symlink atomically (zero-downtime deployment), run database migrations in a backward-compatible way, then reload PHP-FPM to reset OPcache. Containers follow the same steps in an image build. Keep PHP and dependencies updated (composer audit). See Deploying PHP Applications.

Code reading: values, handles and finally

The first program passes an array and two objects to a function. Predict the three numbers.

PHP Predict the output: arrays vs objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Why is the output 3 4 99?

The array is passed by value, so the function appends to its own copy (copy-on-write makes the copy only at that moment), and the caller's $list keeps 3 elements. ArrayObject is an object, and the function receives a copy of the handle, so appending changes the caller's object: 4 elements. The same handle lets the function set $obj->n = 99. Assigning a new object to $obj only rebinds the function's local variable, so the caller never sees the 0.

The second program returns from inside try blocks. Predict all four lines.

PHP Predict the output: return and finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Explain the order and why the exception disappears.

It prints in try, in finally, from try, finally wins. A finally block always runs, even when try returns: the return value is computed first, then finally runs, then the function actually returns. In override(), a return inside finally replaces whatever was happening, including the thrown exception, which is silently discarded. That's why you should never return from finally; use it only for cleanup such as closing files or releasing locks. See Exceptions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump(0 == 'abc'); print in PHP 8?

    PHP 8 changed number-to-string comparisons: when the string isn't numeric, the number is converted to a string and '0' is compared with 'abc'. In PHP 7 the result was true.
  2. 2. $a = ['x' => 1]; $b = ['x' => 2, 'y' => 3]; What is $a + $b?

    The union operator keeps every key of the left array and only adds keys that are missing, so x stays 1 and y is added. array_merge would give x => 2.
  3. 3. Which statement about declare(strict_types=1) is correct?

    strict_types is per file and concerns function calls and returns in that file. It doesn't change operators, and the only scalar coercion it still permits is int to float.
  4. 4. After a foreach loop by reference, what is the recommended fix to avoid the a,b,b bug?

    The loop variable remains a reference to the last element. unset() breaks that reference, so later assignments to a variable with the same name don't change the array.
  5. 5. Why should you never return from a finally block?

    finally always runs last, and a return there wins over everything else, including an exception that was propagating. Use finally only for cleanup.

Summary

  • Junior questions check the foundations: what PHP is and how output works, single vs double quotes, == vs === and PHP 8's comparison rules, types, isset/empty/is_null, include vs require, arrays as ordered maps, bytes vs characters, superglobals, GET vs POST, and cookies vs sessions.
  • Mid-level questions focus on functions and objects: strict_types, passing by value and by handle, closures and arrow functions, match, the null-safe operators, interfaces vs abstract classes, traits, self vs static, visibility, readonly, enums, magic methods and cloning, plus the Throwable hierarchy and the big security topics (SQL injection, XSS, CSRF, password hashing).
  • Senior questions dig into how PHP runs (FPM, shared-nothing, OPcache, JIT, memory and copy-on-write), generators and fibers, Composer and PSRs, dependency injection and SOLID, variance, testing and static analysis, unserialize dangers, performance work, recent versions and deployment.
  • In every answer, a precise explanation, a tiny example, the trap and the tool that catches it are what interviewers reward.

You've reached the end of the PHP course. Keep practicing with the exercises and the 50 classic programs, keep the cheat sheet close, and come back to the PHP course overview whenever you want to review a topic. Happy coding!