“isset checks a variable exists and isn’t null. empty is true for missing variables and any falsy value, including 0 and the string '0'. is_null is a strict null check. For user input I prefer $_POST['x'] ?? '' with explicit validation, because empty treats a valid quantity of 0 as missing.”
Traps that make people fail
Using empty() on a field where 0 is a valid value.
?: (Elvis) uses the fallback when the left side is falsy; 0 is falsy, so it prints 10. ?? (null coalescing) uses the fallback only when the left side is null or missing; 0 exists, so it prints 0.
Say it like this in the interview
“10 0. The short ternary falls back on any falsy value, while ?? only falls back on null or an undefined key, so it keeps the zero.”
By default PHP quietly converts types: pass '5' to a function expecting int and it becomes 5. Strict types turns that off for that file, so a wrong type throws an error instead of being silently converted.
Say it like this in the interview
“It enables strict scalar type checking for calls made from that file: passing a string to an int parameter throws a TypeError instead of coercing. It must be the first statement, and it applies per file, based on the calling file. I use it in all new code with typed properties and return types.”
An HTTP response is a letter: headers (envelope) first, then body (the letter). Once you’ve printed anything (even one space), the envelope is sealed and posted. Calling header(), setcookie() or session_start() after that is too late.
Say it like this in the interview
“Something produced output before the header call. Common culprits: whitespace before <?php or after a closing ?>, a UTF-8 BOM in the file, an echo or debug print, or a PHP warning printed earlier. The error message tells me which file and line started output. Fixes: remove the stray output, omit closing ?> in pure PHP files, or redirect earlier in the request lifecycle (e.g. template_redirect in WordPress).”
Traps that make people fail
Using ob_start() to hide the problem instead of finding the source.
header('Content-Type: text/csv');
$out = fopen('php://output', 'w');
$stmt = $pdo->query('SELECT id, email FROM users', PDO::FETCH_ASSOC);
foreach ($stmt as $row) { // one row at a time
fputcsv($out, $row);
}
fclose($out);
// or generators for your own data sources
function rows(PDO $pdo): Generator { /* yield $row; */ }
In simple words
The script tries to hold the whole warehouse in its hands at once. Instead, carry one box at a time: read rows in chunks and write them out immediately.
Say it like this in the interview
“Raising memory_limit only delays the problem. I stream: iterate the result set row by row with an unbuffered query or chunked LIMIT/keyset pagination, write each row directly to the output with fputcsv, and use generators for transformations. For very large exports I’d run it as a background job and email a download link.”
Time zones. The server, PHP, the database and the user can all have different ideas of “now”.
Say it like this in the interview
“I check date.timezone in php.ini or date_default_timezone_get(), the database timezone, and how values are stored. Best practice: store UTC everywhere, use DateTimeImmutable with explicit DateTimeZone, and convert to the user’s timezone only for display.”
array_filter keeps items that pass a test, array_map transforms each item, array_column pulls one field out of every row, and sort sorts in place (it returns true, not the array).
“array_filter with an arrow function to keep active users, array_column to pluck the emails, then sort. Note sort modifies the array by reference and returns a boolean, so I don’t assign its result.”
Traps that make people fail
Writing $emails = sort($emails), which sets $emails to true.
Forgetting array_filter preserves keys, so $active[0] may not exist; use array_values if you need 0-based keys.
$items = [1, 2, 3];
foreach ($items as &$item) {}
foreach ($items as $item) {}
print_r($items);
In simple words
After the first loop, $item is still a reference (alias) to the last element. The second loop assigns each value into $item, which keeps overwriting the last slot: 1, then 2, then 2 again.
Say it like this in the interview
“[1, 2, 2]. The reference from the first loop survives, so the second loop writes into the last element. Always unset($item) after a by-reference foreach.”
array_merge appends and renumbers numeric keys. The + operator keeps the left array and only adds keys that don’t exist yet.
Say it like this in the interview
“[1, 2, 3, 4] vs [1, 2]. With +, keys 0 and 1 already exist on the left, so the right values are ignored. For string keys, array_merge lets later values overwrite, while + keeps the first.”
They all sort, but they treat keys differently. sort throws keys away, asort keeps each value’s key, ksort sorts by key, usort uses your own compare rule.
Say it like this in the interview
“sort sorts values and reindexes; asort sorts values preserving keys; ksort sorts by keys; usort uses a custom comparator, and with the spaceship operator <=> it’s concise: usort($users, fn($a, $b) => $a['age'] <=> $b['age']). All sort in place.”
Interface = a contract: “anything that is a PaymentGateway must have charge().” No code, just promises. A class can sign many contracts.
Abstract class = a half-built base: some shared code plus some methods children must fill in. A class can extend only one.
Trait = copy-paste of methods into a class, for sharing helpers without inheritance.
interface PaymentGateway { public function charge(int $cents): bool; }
abstract class BaseGateway implements PaymentGateway {
protected function log(string $m): void { error_log($m); }
}
trait Retries {
public function retry(callable $fn, int $times = 3) { /* ... */ }
}
final class StripeGateway extends BaseGateway {
use Retries;
public function charge(int $cents): bool { $this->log('charging'); return true; }
}
Say it like this in the interview
“An interface defines method signatures with no implementation; classes can implement several, which is great for swapping implementations and for dependency injection. An abstract class can hold shared state and code plus abstract methods, but you can only extend one. A trait is a horizontal code-reuse mechanism: its methods are copied into the class. I prefer interfaces plus composition over deep inheritance.”
They will probably ask next
“What is SOLID?” See the senior questions.
“What does static vs self mean?” Late static binding: static refers to the called class.
SOLID is five habits that keep code easy to change:
Single responsibility: one class, one reason to change.
Open/closed: add new behaviour by adding code, not editing old code.
Liskov: a child class must work wherever the parent works.
Interface segregation: small focused interfaces.
Dependency inversion: depend on interfaces, and pass dependencies in.
// Before: OrderService creates its own mailer and gateway (hard to test/change)
// After: depend on abstractions, injected from outside
final class OrderService {
public function __construct(
private PaymentGateway $payments,
private Mailer $mailer,
) {}
public function checkout(Order $order): void {
$this->payments->charge($order->total());
$this->mailer->send(new OrderConfirmation($order));
}
}
Say it like this in the interview
“The two I apply most are single responsibility and dependency inversion. For example, an OrderService receives a PaymentGateway interface through its constructor instead of creating new Stripe() itself. Adding PayPal becomes a new class implementing the interface, which is open/closed, and in tests I inject a fake gateway. I’m pragmatic: I don’t create interfaces for things that will only ever have one implementation.”
class A {
public static function name() { return 'A'; }
public static function viaSelf() { return self::name(); }
public static function viaStatic() { return static::name(); }
}
class B extends A {
public static function name() { return 'B'; }
}
echo B::viaSelf() . ' ' . B::viaStatic();
In simple words
self means “the class where this code is written”. static means “the class that was actually called” (late static binding). Child classes see the difference.
Say it like this in the interview
“A B. self::name() is resolved at compile time to A, while static::name() resolves at runtime to the called class, B. Late static binding is what makes static factory methods like static::create() return the subclass.”
Magic methods are special methods PHP calls automatically at certain moments: when an object is created, converted to a string, or when you access a property that doesn’t exist.
Say it like this in the interview
“__construct and __destruct for lifecycle, __get and __set for inaccessible properties, __call and __callStatic for undefined methods (used by Laravel facades and Eloquent), __toString for string conversion, __invoke to make objects callable, and __serialize/__unserialize for serialization. I use them sparingly because they hide behaviour from IDEs and static analysis.”
Write one contract (Notifier) that every channel follows, and have your code depend on the contract, not on a specific channel. Swapping becomes a configuration change.
Say it like this in the interview
“Define a Notifier interface with send(Message $m), implement EmailNotifier, SmsNotifier, SlackNotifier, and inject the interface into services. A factory or the DI container chooses the implementation from config. For several channels at once, a CompositeNotifier loops over them. This is the strategy pattern plus dependency inversion, and tests can inject a fake.”
PHP refuses to guess which one you want and throws a fatal error, unless you tell it explicitly which to use.
Say it like this in the interview
“It’s a fatal error unless resolved with insteadof, and I can keep the other under an alias with as. For example use A, B { A::hello insteadof B; B::hello as helloFromB; }.”
Composer is PHP’s package manager (like npm for JS). PSR-4 is a rule that maps namespace → folder, so PHP can find App\Models\User in src/Models/User.php automatically. No more long lists of require lines.
“Composer manages dependencies declared in composer.json and locks exact versions in composer.lock, which I commit so every environment installs the same versions. PSR-4 maps a namespace prefix to a directory, and Composer generates an autoloader so classes load on first use. After adding a namespace mapping, I run composer dump-autoload.”
Two libraries might both have a class called User. Namespaces are like surnames: App\Models\User and Vendor\Auth\User can live together.
Say it like this in the interview
“Namespaces prevent name collisions and organise code. Combined with PSR-4 autoloading, the namespace maps to the folder structure. I import with use statements and alias with as when two classes share a name.”
PHP Standards Recommendations: shared rules so libraries and frameworks work together and code looks consistent.
Say it like this in the interview
“PSR-1 and PSR-12 for coding style, PSR-4 for autoloading, PSR-3 for logger interfaces, PSR-7 and PSR-15 for HTTP messages and middleware, PSR-11 for containers, PSR-6 and 16 for caching. They let me swap a logger or HTTP client without rewriting code.”
PHP 8 made code shorter and safer. Knowing these signals that you work with modern PHP, not 2012 tutorials.
// match: strict, returns a value, no fall-through
$label = match ($status) { 'paid' => 'Done', 'failed', 'void' => 'Problem', default => 'Pending' };
// nullsafe operator
$city = $user?->getAddress()?->city;
// named arguments
htmlspecialchars($text, double_encode: false);
// constructor property promotion + readonly
final class Money { public function __construct(public readonly int $cents, public readonly string $currency) {} }
// enums (8.1)
enum Status: string { case Paid = 'paid'; case Failed = 'failed'; }
Say it like this in the interview
“match expressions, the nullsafe operator, named arguments, constructor property promotion, union types, attributes, and from 8.1 enums, readonly properties and first-class callables. Also the JIT, and stricter string-to-number comparisons that fixed old 0 == 'abc' bugs.”
Enums give you a fixed list of allowed values that the language enforces. No more typos like 'pendng'.
enum OrderStatus: string {
case Pending = 'pending';
case Paid = 'paid';
case Refunded = 'refunded';
public function label(): string {
return match ($this) {
self::Pending => 'Awaiting payment',
self::Paid => 'Paid',
self::Refunded => 'Refunded',
};
}
}
$status = OrderStatus::tryFrom($_GET['status'] ?? '') ?? OrderStatus::Pending;
Say it like this in the interview
“A backed enum with tryFrom for parsing input, and methods on the enum for behaviour like labels. Type hints can then require OrderStatus instead of any string.”
A readonly property can be set once (in the constructor) and never changed. Immutable objects can’t be changed by surprise from somewhere else in the code.
Say it like this in the interview
“Readonly properties, and readonly classes in 8.2, can only be initialised once. Immutable value objects like Money or DateRange are safer to pass around, easier to reason about and test. To ‘change’ one, I return a new instance with a with…() method.”
A prepared statement sends the SQL shape first and the user’s data separately, so data can never become SQL code. Like a form with fixed boxes: whatever someone writes in the box stays in the box.
$pdo = new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE email = :email');
$stmt->execute(['email' => $_POST['email']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Say it like this in the interview
“Prepared statements with bound parameters, never string concatenation. I set error mode to exceptions, disable emulated prepares, and use utf8mb4. That prevents SQL injection; output still needs escaping with htmlspecialchars to prevent XSS.”
Never store the password itself, and never use md5/sha1 (too fast, easy to crack). Store a slow, salted hash. When someone logs in, hash what they typed and compare.
$hash = password_hash($password, PASSWORD_DEFAULT); // bcrypt/argon2 with salt
if (password_verify($input, $hash)) {
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) { /* update stored hash */ }
}
Say it like this in the interview
“password_hash with PASSWORD_DEFAULT, which salts automatically and uses bcrypt or Argon2, and password_verify to check. I call password_needs_rehash on login to upgrade old hashes. MD5 and SHA-1 are fast hashes, unsuitable for passwords.”
unserialize can recreate any object type, and creating or destroying certain objects automatically runs code (__wakeup, __destruct). An attacker can craft input that chains these into running their own code.
Say it like this in the interview
“It enables PHP object injection: crafted payloads instantiate classes whose magic methods form a ‘gadget chain’ leading to file writes or remote code execution. I use json_decode for untrusted data, or unserialize with ['allowed_classes' => false].”
“htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') at output time, in every HTML context. For URLs I validate the scheme, and for JavaScript contexts I use json_encode with the HEX flags. Template engines like Blade and Twig escape by default.”
The visitor chooses which file the server runs. They can walk out of the folder with ../ and include sensitive files, or worse.
Say it like this in the interview
“It’s a local, and potentially remote, file inclusion vulnerability. I map allowed page names to files with a whitelist, for example match ($page) { 'about' => 'about.php', default => '404.php' }, never building paths from raw input.”
A cookie is a small note stored in the user’s browser and sent back on every request; the user can read and change it. A session keeps the data on the server; the browser only holds a random ID (in a cookie) like a cloakroom ticket.
Say it like this in the interview
“Cookies live client-side and are sent with every request, so I never store sensitive data in them unless it’s signed or encrypted. Sessions store data server-side, referenced by a session ID cookie. I set session cookies HttpOnly, Secure and SameSite=Lax, and regenerate the ID on login with session_regenerate_id(true) to prevent session fixation.”
They will probably ask next
“How do sessions work with multiple servers?” Store them in Redis or the database instead of local files.
Cookie flags tell the browser how carefully to handle the cookie.
Say it like this in the interview
“HttpOnly so JavaScript can’t read it (limits XSS damage), Secure so it’s only sent over HTTPS, SameSite=Lax or Strict to block most CSRF, a sensible lifetime, and a __Host- prefix where possible. In PHP: session.cookie_httponly, session.cookie_secure, session.cookie_samesite.”
“Set Content-Type: application/json, an http_response_code, and json_encode with JSON_THROW_ON_ERROR. For errors I return a consistent shape like { "error": "..." } with a 4xx or 5xx code.”
Nginx is the receptionist: it serves images and CSS itself, and passes .php requests to PHP-FPM, a pool of PHP workers. Each request starts fresh (“share-nothing”): nothing stays in memory between requests. OPcache saves the compiled version of your PHP files so they don’t have to be re-read and compiled on every request.
Say it like this in the interview
“Nginx handles static files and forwards PHP requests over FastCGI to PHP-FPM, which manages a pool of worker processes. Each request bootstraps the app from scratch and shares nothing, which makes PHP simple to scale horizontally. OPcache stores precompiled bytecode in shared memory, which is a big performance win; in production I disable timestamp validation and reset the cache on deploy. Pool size, pm.max_children, is tuned to available memory divided by per-worker memory.”
They will probably ask next
“What changes with Swoole, RoadRunner or FrankenPHP?” Long-running workers keep the app in memory, which is faster but introduces state-leak risks between requests.
The browser asks the web server for a page; the server hands .php files to PHP; PHP runs your script from top to bottom, talks to the database, builds HTML, sends it back, and then forgets everything.
Say it like this in the interview
“The web server receives the request and passes it to PHP-FPM over FastCGI. PHP loads the script, using OPcache bytecode if available, populates superglobals like $_GET and $_SERVER, runs the code, which bootstraps the framework, routes and queries the database, sends headers and body, and then frees all memory. Each request is isolated, which is PHP’s share-nothing model.”
$rate = 10;
$show = function () use ($rate) { return $rate; };
$rate = 20;
echo $show();
In simple words
A normal closure copies outside variables in with use at the moment it’s created. Changing the variable later doesn’t affect the copy. Arrow functions (fn) also capture by value automatically.
Say it like this in the interview
“10. use ($rate) captures the value at definition time. To capture by reference I’d write use (&$rate), which would print 20.”
A generator gives you values one at a time with yield, pausing in between, instead of building a huge array first. Like a tap instead of a bucket.
function readLines(string $path): Generator {
$file = fopen($path, 'r');
try {
while (($line = fgets($file)) !== false) {
yield rtrim($line, "\n");
}
} finally {
fclose($file);
}
}
foreach (readLines('huge.log') as $line) { /* one line in memory at a time */ }
Say it like this in the interview
“A function containing yield returns a Generator that produces values lazily. It keeps memory constant when iterating large files or query results, and can be chained with foreach. yield from delegates to another iterable.”
In modern PHP, both your own exceptions and most engine errors (calling a method on null, wrong types) are objects you can catch. Throwable is the parent of both.
Say it like this in the interview
“PHP 7+ turned most fatal errors into Error objects. Exception and Error both implement Throwable. I catch specific exceptions where I can recover, let unexpected ones bubble up to a global handler that logs and shows a generic message, and use finally for cleanup. I create domain exceptions like PaymentFailedException rather than throwing generic ones.”
Measure first: find which part is slow (database, loops, external calls), then fix the biggest part.
Say it like this in the interview
“Profile with Xdebug, Blackfire or Tideways. Usual suspects: N+1 queries, missing indexes, queries inside loops, uncached external API calls, loading huge arrays into memory, and repeated work that could be cached in Redis or APCu. Also make sure OPcache is on and PHP is a current version. I re-measure after each change.”
A good senior teaches the process, not just the fix, so the junior can solve the next one alone.
Say it like this in the interview
“I’d pair with them and ask them to explain what they expected versus what happens, then guide them to reproduce it, read the error and stack trace, add logging or an Xdebug breakpoint, and narrow it down. I let them type. Afterwards we add a test for the bug and I share what to look for next time.”