PHP 8 Basics
1. What is PHP and why is it still relevant in 2026?
PHP is a server-side scripting language that still powers about 75% of all websites with a known server-side language — WordPress, Wikipedia, Slack, Etsy, Facebook's legacy stack. PHP 8.3 added JIT, typed class constants, readonly classes, and match, making modern PHP look much closer to TypeScript or Python than the PHP of 10 years ago.
2. Difference between == and === ?
== compares values after type juggling (0 == "0" is true).
=== compares both value and type (0 === "0" is false). Use === by default to avoid subtle bugs.
3. What's new in PHP 8 vs 7?
- JIT compiler — 1-3× speedup for compute-heavy workloads.
- Named arguments —
send(to: $a, subject: $s). matchexpression — strict, value-returning alternative toswitch.- Constructor property promotion — declare + assign properties in the constructor signature.
- Union & nullable types —
int|string,?User. - Attributes — first-class metadata for things like routing, DI, validation.
4. include vs require vs include_once vs require_once?
include— warning if file missing, script continues.require— fatal error if file missing.*_once— skips the file if it has already been included this request. In modern PHP, Composer's autoloader replaces all of these.
OOP and Modern Features
5. final, abstract, interface — when to use which?
finalclass / method — no one can extend / override. Use for security-critical or value objects.abstractclass — partial implementation; subclasses must finish it. Use when you have shared state + abstract methods.interface— pure contract, no implementation. Use when many classes share a capability (Cacheable,JsonSerializable).
6. What is a Trait?
A horizontal code-reuse mechanism (single inheritance + many traits). Useful when two unrelated classes need the same method — e.g. Loggable, Timestampable — without sharing a base class.
7. Late static binding (static:: vs self::)?
self:: resolves at compile time to the class where the method was written.
static:: resolves at runtime to the actual class — required for factory methods that should return the child class:
class A { public static function make(): self { return new static(); } }
class B extends A {}
B::make(); // returns B instance, not A
Database
8. PDO vs mysqli — which to pick?
PDO supports many databases (MySQL, Postgres, SQLite, MSSQL, …) and has named parameters. Mysqli is MySQL-only and slightly faster for simple queries. For new projects, PDO is the default.
9. How do you prevent SQL injection in PHP?
Use prepared statements with parameter binding — never concatenate user input into SQL.
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);
10. What is the N+1 query problem?
Looping over a list and firing a child query per item — 1 list query + N child queries = bad. Fix by eager-loading or joining in one round trip.
Security
11. How do you store passwords securely?
password_hash($pw, PASSWORD_DEFAULT) to hash, password_verify() to check. Never use md5 / sha1 / your own salt scheme.
12. How do you prevent XSS?
Escape all output by destination:
- HTML body / attribute:
htmlspecialchars($s, ENT_QUOTES, "UTF-8") - URL:
urlencode($s) - JSON:
json_encode()— never string concat.
Also serve a strict Content Security Policy header.
13. CSRF — what is it and how to defend?
Cross-Site Request Forgery: an attacker tricks a logged-in user's browser into firing a state-changing request to your site. Defence: synchroniser token in a hidden form field, verified on the server with hash_equals(); plus SameSite=Lax cookies.
Sessions and State
14. How do PHP sessions work?
session_start() issues a PHPSESSID cookie. The server stores session data on disk (or Redis) keyed by that ID. After login, always call session_regenerate_id(true) to prevent session fixation.
15. Cookie vs Session — when to pick which?
| Cookie | Session | |
|---|---|---|
| Stored on | Client | Server |
| Visible to user | Yes | No |
| Max size | 4 KB | Practically unlimited |
| Best for | Theme, locale, anonymous cart | Auth, sensitive flags |
Frameworks
16. Why Laravel?
Convention over configuration, batteries-included (queues, mail, scheduler, Eloquent ORM, Blade templating, validation, authentication). The fastest mainstream way to ship a PHP web app in 2026.
17. What is Eloquent and what's the N+1 trap inside it?
Eloquent is Laravel's Active Record ORM — one class per table. The N+1 trap:
foreach (Post::all() as $p) echo $p->author->name; // 1 + N queries
foreach (Post::with('author')->get() as $p) echo $p->author->name; // 2 queries
with('author') eager-loads the relationship.
18. Sanctum vs Passport?
- Sanctum — lightweight token-based auth for SPAs and mobile apps; the default for new projects.
- Passport — full OAuth2 server; pick only if you genuinely need to be an OAuth2 provider.
Performance
19. How do you make a PHP app fast?
- Turn on OPcache in production (
opcache.enable=1). composer install --no-dev --optimize-autoloader.- Cache framework artefacts:
php artisan config:cache route:cache view:cache. - Index every WHERE/JOIN/ORDER BY column you actually use.
- Avoid N+1 queries — eager-load.
- Add a CDN + browser cache for static assets.
- Put hot reads behind Redis.
20. What does PHP-FPM do?
A FastCGI process manager that pools long-lived PHP worker processes. It avoids the overhead of spawning a new PHP interpreter per request. Tune pm.max_children, pm.max_requests, and pm.start_servers to your traffic.
Behavioural Questions (Senior)
21. Walk me through how you'd design a URL shortener in PHP.
- Generate a short slug (base-62 of an auto-increment ID, or
bin2hex(random_bytes(4))). - Insert
(slug, target_url, owner_id, expires_at)into the DB. - On hit: lookup slug, 301 to target, fire-and-forget log to a queue.
- Add Redis for the slug→URL lookup so 99% of hits skip the DB.
- Rate-limit creation to stop spam.
22. How do you ship a zero-downtime deploy?
Symlink switching: deploy the new code to a fresh releases/<timestamp>/ folder, run migrations, warm caches, then flip a single current symlink. Tools: Deployer, Envoyer, GitHub Actions + rsync.
23. Tell me about a time you refactored legacy PHP.
Strong answer pattern: name the starting problem (no autoload, mysql_*, mixed concerns), list safe steps you took (introduce Composer, port to PDO + prepared statements, extract domain models, add PHPStan + tests), and the measurable result (fewer bugs, faster CI, easier onboarding).
24. What linters / static analysis tools do you use?
- PHPStan / Psalm — type & null-safety checks.
- PHP-CS-Fixer / PHPCS — coding standard.
- Rector — automated upgrades from PHP 7 → 8, Laravel N → N+1.
25. PSR-12, PSR-4 — what are they?
PSRs are PHP-FIG standards.
PSR-12 — coding style (indentation, naming).
PSR-4 — autoloading by namespace → directory mapping (what Composer uses).
