How to Detect and Fix PHP Memory Leaks
Last updated: 5 November 2026. See the update log at the end.In a normal PHP-FPM request,...
Interview questions
Common PHP interview questions with short, correct answers, up to PHP 8.4. Filter by level or topic, or download them as a PDF.
matching
== compares values after type juggling ('1' == 1 is true). === also compares types, so '1' === 1 is false. Use === by default to avoid surprises; since PHP 8, 0 == 'abc' is false, but loose comparison is still easy to get wrong.
Both output strings. echo can take several arguments and returns nothing; print takes one argument and always returns 1, so it can be used in expressions. echo is marginally faster and far more common.
It makes scalar type declarations strict for function calls made from that file: passing '5' to an int parameter throws a TypeError instead of being converted. It applies per file, to the calls written in that file.
A nullable type ?string accepts a string or null. A union type (PHP 8.0) accepts any of several types: int|float. PHP 8.2 added DNF types such as (A&B)|null, and mixed accepts anything.
isset($x) is true when the variable exists and is not null. empty($x) is true for anything falsy ('', 0, '0', [], null, false) or missing. is_null($x) is true only for null and warns if the variable is undefined.
array_merge() renumbers numeric keys and appends; for string keys the later value wins. + keeps the left array's keys and only adds keys that are missing, so for duplicate keys the left value wins and numeric keys are not appended.
array_map($fn, $array) returns a new array with $fn applied to each element.array_filter($array, $fn) keeps the elements where $fn returns true (keys are preserved).array_reduce($array, $fn, $initial) folds the array into a single value, such as a sum.Double-quoted strings parse variables ("Hello $name") and escape sequences like \n; single-quoted strings are literal (only \' and \\ are escapes). Heredoc behaves like double quotes, nowdoc like single quotes.
Use the mb_ functions (mb_strlen, mb_substr, mb_strtolower). strlen('é') returns 2 because it counts bytes, mb_strlen('é') returns 1. Make sure the database and connection use utf8mb4 too.
An interface only declares methods (and constants) a class must implement; a class can implement many. An abstract class can contain implemented methods, properties and abstract methods; a class can extend only one. Use interfaces for contracts, abstract classes to share code.
Traits let you reuse methods in several unrelated classes (horizontal reuse), since PHP has single inheritance. A class uses a trait and gets its methods as if they were written in the class. Conflicts are resolved with insteadof and as.
$this is the current object. self:: refers to the class where the code is written. static:: uses late static binding: it refers to the class that was actually called, so a parent method calling new static() creates the child class.
__construct, __destruct, __get / __set (inaccessible properties), __call / __callStatic (inaccessible methods), __toString, __invoke (call the object like a function), __isset, __unset, __clone, __serialize / __unserialize. Frameworks use __call and __get heavily, e.g. Eloquent attributes.
Passing a class its dependencies (usually through the constructor) instead of creating them inside. It makes code testable (inject a fake) and flexible (swap implementations). A DI container automates building those objects.
match, nullsafe operator ?->, attributes, JIT.never type.json_validate(), #[\Override].new without parentheses in chains.match is an expression that returns a value, compares strictly (===), has no fall-through and throws UnhandledMatchError when nothing matches. switch compares loosely and needs break statements.
Enums (PHP 8.1) define a fixed set of values: enum Status: string { case Active = 'active'; case Banned = 'banned'; }. Backed enums have scalar values (Status::from('active')), can have methods and implement interfaces. They replace class constants for statuses and types.
A readonly property can be set once, from inside the class (usually the constructor), and never changed afterwards; writing it again throws an Error. A readonly class (8.2) makes all its properties readonly, good for value objects and DTOs.
Structured metadata on classes, methods, properties and parameters, written as #[Route('/users')]. They replace docblock annotations and are read with the Reflection API; frameworks use them for routing, validation and ORM mapping.
Both implement Throwable. Exception is for application problems you expect to handle; Error is for engine problems like calling an undefined method or a TypeError. catch (Throwable $e) catches both.
A finally block runs after try / catch whether an exception was thrown or not, even when the code returns. Use it to release resources, such as closing a file or a lock.
Never display errors to users (display_errors=Off); log them instead (log_errors=On) and show a friendly error page. Report exceptions to a log or service such as Sentry, and use specific exception classes to handle expected cases.
Use prepared statements with bound parameters (PDO: $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$email]);). Never concatenate user input into SQL. Validate input as well, but parameters are the real protection.
Use password_hash($password, PASSWORD_DEFAULT) (bcrypt or Argon2, with a salt built in) and check with password_verify(). Never use md5 or sha1 for passwords, and call password_needs_rehash() after login to upgrade old hashes.
Cross-site scripting: an attacker gets their JavaScript into your page, for example through a comment. Escape all output for its context: htmlspecialchars($value, ENT_QUOTES, 'UTF-8') in HTML. Templates such as Blade or Twig do it automatically. A Content-Security-Policy adds another layer.
Cross-site request forgery: another site makes the user's browser send a request (like changing their email) to your site with their cookies. Prevent it with a secret per-session token in forms that the server checks, plus SameSite cookies.
Cookies are stored in the browser and sent with every request; the user can read and change them. Sessions store data on the server; the browser only holds a session id in a cookie. Keep sensitive data in the session, never in plain cookies.
OPcache stores compiled PHP bytecode in shared memory, so PHP doesn't have to parse and compile scripts on every request. It's one of the biggest free performance wins; in production, opcache.validate_timestamps=0 skips file checks (clear the cache when you deploy).
Composer is PHP's dependency manager and autoloader. composer.json lists the allowed version ranges; composer.lock records the exact installed versions. Commit the lock file and run composer install on servers so everyone gets the same versions.
PHP Standards Recommendations from PHP-FIG that make libraries work together: PSR-4 (autoloading), PSR-12 / PER (coding style), PSR-3 (logger interface), PSR-7 (HTTP messages), PSR-11 (container), PSR-15 (middleware).
A generator function uses yield to return values one at a time instead of building a whole array. Reading a large CSV line by line with a generator keeps memory flat, whatever the file size.
All 32 questions and answers on a printable A4 PDF. Free for newsletter subscribers.
Last updated: 5 November 2026. See the update log at the end.In a normal PHP-FPM request,...
Most lists of "best AI coding prompts" are collections of clever wording. Wording is rarely the...
Laravel Herd is a local development environment for macOS and Windows that runs PHP and nginx...
We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.