PHP knowledge reference Essential PHP Concepts Explore all 86 knowledge cards from one complete menu. Repeated questions from the supplied PHP, OOP, senior, project, security, and CodeIgniter guides have been merged into stronger concepts with concise explanations, memory formulas, examples, and practical uses.
Quick recall Concept Glance Card 30 sec
01 Easy tipServer-side code creates the response. <?php
declare(strict_types=1);
echo 'Hello, PHP!'; 02 Concise explanation“PHP is an open-source server-side language used for websites, APIs, CLI tools, workers, and scheduled jobs. It processes requests and commonly returns HTML or JSON.”
03 Memory formulaRequest + PHP logic + services = response04 Real-world usesweb applications APIs CLI tools background jobs Concept 02 What are PHP’s main strengths and trade-offs? Quick recall Concept Glance Card 30 sec
01 Easy tipMature web tooling, with legacy edges to manage. 02 Concise explanation“PHP offers broad hosting, Composer, strong frameworks, database support, and productive web APIs. Its long history also brings inconsistent legacy APIs, loose coercion, and outdated examples, so supported versions, types, tests, standards, and static analysis matter.”
03 Memory formulaMature ecosystem + disciplined modern practices = productive PHP04 Real-world usestechnology selection legacy modernisation team standards Concept 03 How do static and dynamic websites differ? Quick recall Concept Glance Card 30 sec
01 Easy tipStatic is prebuilt; dynamic uses data or context. 02 Concise explanation“A static site serves prebuilt files. A dynamic site generates or adapts responses using application logic, request context, databases, or APIs. Many systems combine both approaches.”
03 Memory formulaPrebuilt content vs generated response04 Real-world usesarchitecture decisions caching personalisation Concept 04 How is PHP executed? Quick recall Concept Glance Card 30 sec
01 Easy tipWeb requests and CLI scripts use the same runtime differently. php script.php --dry-run 02 Concise explanation“A web server or process manager passes requests to PHP, while CLI scripts run with php script.php and receive arguments through $argv and $argc. CLI mode suits migrations, imports, workers, and scheduled jobs.”
03 Memory formulaWeb request or CLI command -> PHP runtime04 Real-world usesweb serving cron jobs queue workers migrations Concept 05 How does PHP source become executable work? Quick recall Concept Glance Card 30 sec
01 Easy tipParse to opcodes, then execute. 02 Concise explanation“PHP source is tokenised, parsed into a syntax structure, compiled to opcodes, and executed by the Zend Engine. OPcache can retain compiled opcodes between requests.”
03 Memory formulaSource -> tokens -> syntax tree -> opcodes -> execution04 Real-world usesruntime debugging performance reasoning static analysis Concept 06 How do PHP, HTML, and JavaScript interact? Quick recall Concept Glance Card 30 sec
01 Easy tipPHP generates; HTML describes; JavaScript interacts. 02 Concise explanation“PHP runs on the server and can generate HTML or JSON. The browser renders HTML and executes delivered JavaScript. Forms and browser requests send data back to PHP endpoints.”
03 Memory formulaPHP response -> browser HTML/JS -> new HTTP request04 Real-world usesserver rendering forms progressive enhancement Concept 07 How should PHP values be passed to JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipEncode data as JSON, never hand-build JavaScript strings. const value = <?= json_encode($value, JSON_HEX_TAG | JSON_HEX_AMP) ?>; 02 Concise explanation“Use json_encode() with suitable hex flags for inline data, or expose a JSON endpoint for larger datasets. This preserves syntax and prevents quotes or markup from changing the script context.”
03 Memory formulaPHP value + JSON encoding = safe JavaScript data04 Real-world usesserver-rendered configuration API payloads XSS prevention Concept 08 What are PEAR, Composer, and Packagist? Quick recall Concept Glance Card 30 sec
01 Easy tipPEAR is legacy; Composer and Packagist are modern. 02 Concise explanation“PEAR is an older package repository and distribution system. Modern PHP projects declare dependencies in composer.json, resolve exact versions into composer.lock, and commonly download packages from Packagist.”
03 Memory formulacomposer.json + composer.lock + Packagist = reproducible dependencies04 Real-world usesdependency management legacy maintenance reproducible builds Concept 09 Which PHP frameworks and platforms are common? Quick recall Concept Glance Card 30 sec
01 Easy tipKnow the tool and why it fits. 02 Concise explanation“Laravel, Symfony, CodeIgniter, CakePHP, Yii, and Slim are common frameworks. WordPress, Drupal, Joomla, TYPO3, Magento, and WooCommerce are major PHP platforms. Routing, DI, middleware, validation, persistence, and testing knowledge matters more than listing names.”
03 Memory formulaFramework conventions + project fit > name list04 Real-world usesproject selection legacy work web platforms Concept 10 What types does PHP support? Quick recall Concept Glance Card 30 sec
01 Easy tipEight core runtime types plus modern declaration types. 02 Concise explanation“Core values include int, float, string, bool, array, object, null, and resource. Declarations also support callable, iterable, mixed, void, never, literal types, unions, and intersections where appropriate.”
03 Memory formulaScalar + compound + special + declaration types04 Real-world usesAPI contracts domain modelling static analysis Concept 11 What are PHP variable naming and case-sensitivity rules? Quick recall Concept Glance Card 30 sec
01 Easy tipVariables are case-sensitive; consistent casing avoids surprises. 02 Concise explanation“Variables begin with $, then a letter or underscore, followed by letters, numbers, or underscores. Variable names are case-sensitive; class and function names are generally case-insensitive, but consistent conventional casing should always be used.”
03 Memory formula$ + valid name; casing stays consistent04 Real-world usesreadable code coding standards debugging Concept 12 How do variables and constants differ? Quick recall Concept Glance Card 30 sec
01 Easy tipVariables change; constants name fixed values. 02 Concise explanation“Variables use $, follow scope rules, and may be reassigned. const declares ordinary constants, define() supports runtime definition, and constant() resolves a constant whose name is held in a string.”
03 Memory formulaVariable = mutable name; constant = fixed name04 Real-world usesconfiguration constants domain values runtime lookup Concept 13 How do type declarations and strict_types work? Quick recall Concept Glance Card 30 sec
01 Easy tipTypes state the contract; strict mode reduces scalar coercion. <?php
declare(strict_types=1);
function total(float $price, int $quantity): float {
return $price * $quantity;
} 02 Concise explanation“PHP supports parameter, return, and property types. declare(strict_types=1) makes applicable scalar calls originating in that file reject incompatible values rather than coerce them; external input still requires explicit validation and conversion.”
03 Memory formulaDeclared types + strict callers = predictable contracts04 Real-world usesservice APIs domain models refactoring safety Concept 14 What is the difference between == and ===? Quick recall Concept Glance Card 30 sec
01 Easy tipLoose converts; strict checks type and value. 02 Concise explanation“== may coerce operands before comparison. === requires matching value and type. Strict comparison is usually safer, especially when functions return a valid zero or false, such as strpos().”
03 Memory formula=== = same type + same value04 Real-world usesinput checks sentinel values bug prevention Concept 15 How are objects compared and copied? Quick recall Concept Glance Card 30 sec
01 Easy tipEqual state differs from identical instance. 02 Concise explanation“For objects, == compares class and property values, while === requires the same instance. Assigning an object variable copies its object handle, so both variables normally refer to one object; clone creates a separate object.”
03 Memory formula== equal state; === same object; clone new object04 Real-world usesidentity maps value objects mutable state Concept 16 What do isset() and empty() check? Quick recall Concept Glance Card 30 sec
01 Easy tipisset means present and non-null; empty means false-like or missing. 02 Concise explanation“isset() is false for undefined or null values. empty() is true for missing values and false-like values including 0, "0", false, an empty string, and an empty array. Use strict checks when zero is meaningful.”
03 Memory formulaisset = exists and not null; empty = false-like04 Real-world usesform handling optional configuration array access Concept 17 How does PHP convert values to Boolean? Quick recall Concept Glance Card 30 sec
01 Easy tipZero, string zero, empty string, empty array, null, and false are false-like. 02 Concise explanation“PHP truthiness treats false, 0, 0.0, an empty string, "0", an empty array, and null as false. Most other values are true, so strict comparison is important when false-like values are valid data.”
03 Memory formulaFalse-like is broader than false04 Real-world usesconditionals validation return-value checks Concept 18 What are variable variables? Quick recall Concept Glance Card 30 sec
01 Easy tipTwo dollar signs use one value as another variable name. 02 Concise explanation“$$name resolves the value of $name as another variable name. It is valid but obscures data flow; arrays or objects are usually clearer and easier to analyse.”
03 Memory formula$name -> variable name -> $$name value04 Real-world useslegacy code metaprogramming dynamic forms Concept 19 How do strings, output, and concatenation work? Quick recall Concept Glance Card 30 sec
01 Easy tipDot joins strings; echo and print output them. 02 Concise explanation“Use . or .= for concatenation. Double-quoted strings interpolate variables and escapes; single-quoted strings have minimal escaping. echo accepts multiple arguments and has no return value; print accepts one and returns 1.”
03 Memory formulaDot joins; echo outputs; print outputs and returns 104 Real-world usestemplates messages CLI output Concept 20 What arrays does PHP provide? Quick recall Concept Glance Card 30 sec
01 Easy tipOne ordered-map type supports list and dictionary shapes. 02 Concise explanation“PHP has one ordered-map array type, commonly used as indexed, associative, or multidimensional arrays. foreach handles arrays and Traversable objects clearly.”
03 Memory formulaOrdered map -> indexed, associative, or nested04 Real-world usescollections configuration JSON data Concept 21 How do array_merge() and array_combine() differ? Quick recall Concept Glance Card 30 sec
01 Easy tipMerge joins values; combine pairs keys with values. 02 Concise explanation“array_merge() joins arrays, overwrites duplicate string keys with later values, and renumbers numeric keys. array_combine() builds an associative array from equally sized key and value arrays.”
03 Memory formulaMerge = join; combine = keys + values04 Real-world usesdata transformation configuration overlays mapping columns Concept 22 How do loops, break, and continue work? Quick recall Concept Glance Card 30 sec
01 Easy tipBreak exits; continue skips. 02 Concise explanation“PHP provides for, while, do-while, and foreach. break exits the current loop or switch; continue skips the remainder of the current iteration.”
03 Memory formulabreak = leave; continue = next iteration04 Real-world usescollection processing search loops batch jobs Concept 23 How do variadic functions handle arguments? Quick recall Concept Glance Card 30 sec
01 Easy tipVariadics make a typed list of extra arguments. 02 Concise explanation“A ...$items parameter collects remaining arguments into an array and can carry a type declaration. Older func_num_args() and func_get_args() remain available but are less explicit.”
03 Memory formula...$items = typed variable-length arguments04 Real-world usesformatters aggregation adapter APIs Concept 24 What is object-oriented programming? Quick recall Concept Glance Card 30 sec
01 Easy tipObjects combine state and behaviour behind responsibilities. 02 Concise explanation“OOP models software with objects and emphasises encapsulation, abstraction, polymorphism, and carefully used inheritance. Modern design also favours composition to combine focused collaborators.”
03 Memory formulaState + behaviour + clear responsibility = object04 Real-world usesdomain modelling service design maintainable systems Concept 25 What is the difference between a class and an object? Quick recall Concept Glance Card 30 sec
01 Easy tipClass is the definition; object is an instance. 02 Concise explanation“A class declares properties and methods. An object is one runtime instance created from that class, with its own state and the class-defined behaviour.”
03 Memory formulaClass + new = object04 Real-world usesdomain entities services value objects Concept 26 What do public, protected, and private mean? Quick recall Concept Glance Card 30 sec
01 Easy tipPublic is open; protected is family; private is declaring class only. 02 Concise explanation“Visibility controls access. Prefer private state by default and expose meaningful behaviour; visibility improves encapsulation but does not encrypt sensitive data.”
03 Memory formulapublic > protected > private access04 Real-world usesencapsulation stable APIs subclass design Concept 27 What do constructors, property promotion, and destructors do? Quick recall Concept Glance Card 30 sec
01 Easy tipConstruct valid state; destruct only non-critical resources. 02 Concise explanation“__construct() establishes valid state and receives dependencies; property promotion declares and assigns properties in its parameter list. __destruct() may perform non-critical cleanup but should not carry essential business work.”
03 Memory formulaConstruct = initialise; destruct = best-effort cleanup04 Real-world usesdependency injection value objects resource wrappers Concept 28 How does inheritance work in PHP? Quick recall Concept Glance Card 30 sec
01 Easy tipOne parent, only for a genuine is-a relationship. 02 Concise explanation“A class can extend one parent and override compatible non-final methods. Multilevel chains are possible, but deep hierarchies increase coupling; use inheritance only when a subtype preserves the parent contract.”
03 Memory formulaOne parent + substitutable child = valid inheritance04 Real-world usesframework extension template methods specialised types Concept 29 Why does PHP not support multiple class inheritance? Quick recall Concept Glance Card 30 sec
01 Easy tipAvoid parent ambiguity; combine contracts and collaborators instead. 02 Concise explanation“Multiple parents can create method ambiguity and the diamond problem. PHP instead allows multiple interfaces, multiple traits, and object composition.”
03 Memory formulaOne class parent + many interfaces/traits + composition04 Real-world usesrole modelling API design conflict avoidance Concept 30 What are traits and how are conflicts resolved? Quick recall Concept Glance Card 30 sec
01 Easy tipTraits reuse small implementation blocks horizontally. 02 Concise explanation“Traits insert methods and properties into classes without defining a parent type. Use insteadof to select between conflicts and as to alias methods. Prefer an injected service when behaviour has substantial state or dependencies.”
03 Memory formulaTrait = reuse; insteadof = choose; as = alias04 Real-world usescross-cutting helpers legacy reuse small cohesive behaviour Concept 31 How do interfaces and abstract classes differ? Quick recall Concept Glance Card 30 sec
01 Easy tipInterface defines capability; abstract class provides a shared base. 02 Concise explanation“A class can implement many interfaces, enabling interchangeable implementations. It can extend only one abstract class, which may carry state, constructors, and implemented behaviour for closely related subclasses.”
03 Memory formulaInterface = contract; abstract class = shared base04 Real-world usesdependency inversion polymorphism framework bases Concept 32 What are composition and dependency injection? Quick recall Concept Glance Card 30 sec
01 Easy tipHas-a collaborators supplied from outside. 02 Concise explanation“Composition builds behaviour from collaborating objects. Dependency injection supplies those collaborators externally instead of constructing them inside business classes, making dependencies explicit and replaceable in tests.”
03 Memory formulaComposition + external construction = loose coupling04 Real-world usesunit testing provider replacement application services Concept 33 What are magic methods? Quick recall Concept Glance Card 30 sec
01 Easy tipAutomatic hooks with double-underscore names. 02 Concise explanation“Methods such as __construct, __get, __set, __call, __invoke, __toString, __clone, and __serialize are triggered by defined language events. Use dynamic hooks sparingly because they can hide mistakes and weaken static analysis.”
03 Memory formula__name = PHP-triggered object hook04 Real-world usesvalue formatting callable objects serialisation Concept 34 What is late static binding? Quick recall Concept Glance Card 30 sec
01 Easy tipself means defining class; static means runtime-called class. 02 Concise explanation“Inside inherited static code, self:: resolves to the class that defines the method, while static:: follows the class called at runtime. It supports extensible factories and base-class APIs.”
03 Memory formulaself = defined here; static = called as04 Real-world usesnamed constructors static factories extensible bases Concept 35 What do final classes and methods guarantee? Quick recall Concept Glance Card 30 sec
01 Easy tipFinal blocks extension or overriding. 02 Concise explanation“A final class cannot be extended, and a final method cannot be overridden. Use final where replacement would violate an important invariant or design guarantee.”
03 Memory formulaFinal class = no child; final method = no override04 Real-world usesvalue objects security-sensitive invariants stable services Concept 36 How do overloading and overriding differ in PHP? Quick recall Concept Glance Card 30 sec
01 Easy tipOverride inherited behaviour; simulate overload-style calls. 02 Concise explanation“Overriding supplies a compatible child implementation. PHP does not allow multiple same-named methods with different signatures; optional parameters, variadics, __call(), or explicit method names provide alternatives.”
03 Memory formulaOverride = child replacement; overload = simulated dispatch04 Real-world usesinheritance legacy APIs flexible call shapes Concept 37 What are the SOLID principles? Quick recall Concept Glance Card 30 sec
01 Easy tipFive guides for changeable, testable object design. 02 Concise explanation“SOLID covers single responsibility, open/closed design, Liskov substitution, interface segregation, and dependency inversion. Apply them as design heuristics rather than forcing abstractions into simple code.”
03 Memory formulaSRP + OCP + LSP + ISP + DIP04 Real-world usesservice design refactoring architecture reviews Concept 38 What are PHP superglobals? Quick recall Concept Glance Card 30 sec
01 Easy tipGlobal request containers are inputs, not trusted data. 02 Concise explanation“$GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, and $_ENV are available in every scope. Validate request values and prefer framework request abstractions in application logic.”
03 Memory formulaSuperglobal -> validate -> typed application input04 Real-world usesrequest handling uploads environment access Concept 39 How do GET and POST differ? Quick recall Concept Glance Card 30 sec
01 Easy tipGET retrieves; POST submits or creates. 02 Concise explanation“GET should safely retrieve without changing state and commonly uses a query string. POST sends a body and commonly creates or commands work. POST is not a security control; use HTTPS, validation, authorisation, and CSRF protection where applicable.”
03 Memory formulaHTTP semantics + separate security controls04 Real-world usesforms REST APIs search pages Concept 40 How does PHP process form data? Quick recall Concept Glance Card 30 sec
01 Easy tipCheck method, read the correct input, validate on the server. 02 Concise explanation“Form-encoded values appear in $_GET or $_POST, files in $_FILES, and metadata in $_SERVER. Client validation improves usability but all values require server-side validation.”
03 Memory formulaRequest method + input source + server validation04 Real-world usesregistration checkout search forms Concept 41 How do sessions and cookies differ? Quick recall Concept Glance Card 30 sec
01 Easy tipBrowser stores cookies; server normally stores session state. 02 Concise explanation“Cookies are client-controlled values sent with matching requests. PHP sessions usually keep state server-side and identify it with a cookie. Treat cookies as untrusted and keep trusted account state on the server.”
03 Memory formulaCookie = browser value; session = server state + browser ID04 Real-world usesauthentication preferences shopping baskets Concept 42 How should PHP sessions be secured? Quick recall Concept Glance Card 30 sec
01 Easy tipProtect the ID, rotate it, expire it, and store little. 02 Concise explanation“Use HTTPS and Secure, HttpOnly, and appropriate SameSite cookie settings. Regenerate the ID after login or privilege changes, enforce expiry, clear state on logout, and use a shared session store when scaling horizontally.”
03 Memory formulaSecure cookie + ID rotation + expiry + minimal state04 Real-world useslogin sessions multi-instance apps account security Concept 43 How should file uploads be secured? Quick recall Concept Glance Card 30 sec
01 Easy tipError, size, real MIME, random name, safe location. 02 Concise explanation“Check upload errors and count, enforce size limits, detect MIME with finfo, allowlist types, generate names, move with move_uploaded_file(), store outside the public root, prevent execution, authorise access, and scan risky content.”
03 Memory formulaValidate bytes + rename + isolate + authorise04 Real-world usesdocuments avatars media ingestion Concept 44 What do header() and response status functions do? Quick recall Concept Glance Card 30 sec
01 Easy tipHeaders must be sent before body output. 02 Concise explanation“header() sends response headers such as Content-Type or Location before body output; http_response_code() sets status. Framework response objects are easier to test and reduce accidental header construction.”
03 Memory formulaStatus + headers + body = HTTP response04 Real-world usesredirects JSON APIs downloads Concept 45 What is the difference between include and require? Quick recall Concept Glance Card 30 sec
01 Easy tipMissing required file stops; missing included file warns. 02 Concise explanation“include warns and normally continues if loading fails; require raises an Error. The once variants avoid duplicate evaluation. Modern classes should normally use Composer autoloading.”
03 Memory formulaInclude may continue; require cannot; once deduplicates04 Real-world usesbootstrap files optional templates legacy loading Concept 46 What does the @ error-control operator do? Quick recall Concept Glance Card 30 sec
01 Easy tipIt hides diagnostics; it does not handle failure. 02 Concise explanation“@ suppresses normal diagnostic output for an expression, making failures harder to inspect. Check expected failure states and throw or return meaningful results instead.”
03 Memory formulaSuppression != handling04 Real-world useslegacy maintenance file operations error reviews Concept 47 How should passwords be stored? Quick recall Concept Glance Card 30 sec
01 Easy tipHash to store; verify to authenticate; rehash to upgrade. 02 Concise explanation“Use password_hash() with PASSWORD_DEFAULT, password_verify(), and password_needs_rehash(). Store the complete returned hash; never store plaintext or use fast general hashes such as MD5 or SHA-1.”
03 Memory formulahash -> store; verify -> login; rehash -> upgrade04 Real-world usesauthentication credential migration account security Concept 48 How do prepared statements prevent SQL injection? Quick recall Concept Glance Card 30 sec
01 Easy tipKeep SQL structure separate from values. $statement = $pdo->prepare('SELECT id FROM users WHERE email = :email');
$statement->execute(['email' => $email]); 02 Concise explanation“PDO or MySQLi prepared statements bind untrusted values separately from SQL. Placeholders cannot represent identifiers, so table names, columns, and sort directions must come from strict server-controlled allowlists.”
03 Memory formulaParameterise values + allowlist identifiers + least privilege04 Real-world usessearch CRUD report filtering Concept 49 How should output be escaped? Quick recall Concept Glance Card 30 sec
01 Easy tipEscape for the destination context. 02 Concise explanation“Use htmlspecialchars() for HTML text and attributes with appropriate flags, json_encode() for JavaScript data, and framework escaping for templates. Validation does not replace output encoding.”
03 Memory formulaUntrusted value + context encoder = safe output04 Real-world usesXSS prevention templates embedded data Concept 50 How do validation, authentication, authorisation, and CSRF differ? Quick recall Concept Glance Card 30 sec
01 Easy tipValid input, known identity, permitted action, genuine browser intent. 02 Concise explanation“Validation checks shape and business rules; authentication identifies the caller; authorisation checks access to the specific action or resource; CSRF tokens protect cookie-authenticated state changes from forged browser requests.”
03 Memory formulaValidate + authenticate + authorise + CSRF where needed04 Real-world usesprotected forms admin actions multi-tenant APIs Concept 51 How should errors and exceptions be handled? Quick recall Concept Glance Card 30 sec
01 Easy tipCatch specifically, log safely, return generic production messages. 02 Concise explanation“Exception and Error both implement Throwable. Catch only where recovery or translation is meaningful, order specific catches first, use finally for reliable cleanup, centralise uncaught handling, and never expose stack traces or secrets in production.”
03 Memory formulaSpecific handling + safe context + generic response04 Real-world usesAPI errors transaction cleanup service boundaries Concept 52 How should error reporting differ by environment? Quick recall Concept Glance Card 30 sec
01 Easy tipDisplay locally; log, correlate, and alert in production. 02 Concise explanation“Development should report and display relevant errors. Production should log rather than render details, with structured context, request IDs, redaction, aggregation, and impact-based alerts.”
03 Memory formulaLocal visibility; production observability without leakage04 Real-world usesincident response debugging monitoring Concept 53 How do namespaces and PSR-4 autoloading work? Quick recall Concept Glance Card 30 sec
01 Easy tipNamespace prefixes map class names to directories. 02 Concise explanation“Namespaces organise code and avoid name collisions. Composer PSR-4 mappings translate namespace prefixes into directory roots and generate an autoloader, replacing manual class includes.”
03 Memory formulaNamespace prefix + PSR-4 path = automatic class loading04 Real-world usespackage design application organisation third-party libraries Concept 54 What is PDO and how should connections be configured? Quick recall Concept Glance Card 30 sec
01 Easy tipPortable API, secure configuration, exception mode, full Unicode. 02 Concise explanation“PDO provides a consistent object-oriented API across several relational drivers. Keep credentials outside source control, specify the driver and utf8mb4 where appropriate, enable exception mode, inject connections, and hide internal connection errors from users.”
03 Memory formulaSecure config + PDO options + injected connection04 Real-world usesMySQL access PostgreSQL access transactions Concept 55 How do PDO and MySQLi differ? Quick recall Concept Glance Card 30 sec
01 Easy tipBoth can be safe; PDO supports multiple drivers. 02 Concise explanation“MySQLi targets MySQL and offers procedural and object-oriented APIs. PDO offers one object-oriented interface for several database drivers. Both support prepared statements; project requirements and existing architecture should decide.”
03 Memory formulaPDO = multiple drivers; MySQLi = MySQL-specific04 Real-world usesdatabase selection legacy code data layers Concept 56 How should transactions be used? Quick recall Concept Glance Card 30 sec
01 Easy tipKeep related writes atomic and transactions short. 02 Concise explanation“Begin a transaction for changes that must succeed together, commit only after all database work succeeds, and roll back on failure. Avoid slow external calls inside transactions and handle deadlocks or retries only when the operation is safe.”
03 Memory formulaBegin + related writes + commit, else rollback04 Real-world usescheckout inventory updates financial records Concept 57 What is MVC in PHP? Quick recall Concept Glance Card 30 sec
01 Easy tipController coordinates; model decides; view presents. 02 Concise explanation“MVC separates request coordination, domain/data behaviour, and presentation. Models are broader than database rows, views own presentation and escaping, and controllers should remain thin by delegating workflows to application services.”
03 Memory formulaRequest -> controller -> application/model -> view or JSON04 Real-world usesframework applications testable controllers separation of concerns Concept 58 How should a REST API be designed? Quick recall Concept Glance Card 30 sec
01 Easy tipResources, HTTP semantics, consistent contracts, and policy checks. 02 Concise explanation“Use resource-oriented URLs, correct methods and status codes, validation, authentication, resource-level authorisation, pagination, stable JSON shapes, documented versioning, rate limits, and generic production errors.”
03 Memory formulaResource + method + policy + representation04 Real-world usesmobile backends SPAs service integrations Concept 59 How should third-party API calls be made? Quick recall Concept Glance Card 30 sec
01 Easy tipTimeout everything and retry only safe failures. 02 Concise explanation“Use a maintained HTTP client with TLS verification, connection and response timeouts, status validation, controlled retries with backoff for safe operations, circuit breaking where useful, and SSRF protection for dynamic destinations.”
03 Memory formulaTimeout + validate + safe retry + observe04 Real-world usespayment providers email APIs service-to-service calls Concept 60 How should email verification tokens work? Quick recall Concept Glance Card 30 sec
01 Easy tipRandom, expiring, single-use, and safely stored. 02 Concise explanation“Generate a cryptographically random token, store a hash where practical, set an expiry, validate once, mark the address verified, invalidate the token, rate-limit resends, and avoid account enumeration.”
03 Memory formulaRandom + hash + expiry + one use04 Real-world usesregistration email changes account recovery Concept 61 How should a slow PHP application be optimised? Quick recall Concept Glance Card 30 sec
01 Easy tipMeasure, profile, fix the bottleneck, and retest. 02 Concise explanation“Baseline latency, throughput, errors, CPU, and memory; trace the request; inspect query plans and N+1 access; reduce work and payloads; cache deliberately; queue non-critical tasks; tune OPcache and PHP-FPM; then repeat the same load test.”
03 Memory formulaMeasure -> profile -> database/cache/queue/runtime -> retest04 Real-world usesproduction tuning capacity planning incident remediation Concept 62 What do OPcache, application caches, and HTTP caches do? Quick recall Concept Glance Card 30 sec
01 Easy tipCache compiled code, reusable data, and responses at different layers. 02 Concise explanation“OPcache retains compiled opcodes. Redis or Memcached can store reusable application data. HTTP caches and CDNs reuse responses or assets. Each layer needs clear keys, scope, expiry, invalidation, and observability.”
03 Memory formulaOpcode cache + data cache + response cache04 Real-world useslatency reduction load reduction scaling Concept 63 What are generators? Quick recall Concept Glance Card 30 sec
01 Easy tipyield produces one item and resumes later. 02 Concise explanation“A generator lazily yields values instead of first building a complete array. It can reduce memory for large files, paginated APIs, and pipelines, provided the producer and consumer do not accumulate everything elsewhere.”
03 Memory formulayield one -> process -> resume04 Real-world useslarge CSV files streaming data batch imports Concept 64 How should long-running work be handled? Quick recall Concept Glance Card 30 sec
01 Easy tipUse monitored workers rather than unlimited web requests. 02 Concise explanation“set_time_limit(0) only removes PHP’s own limit in applicable environments; proxies and process managers may still time out. Queue workers or CLI processes provide better retries, supervision, and observability.”
03 Memory formulaLong work -> queue/CLI worker, not web request04 Real-world usesreports media processing bulk imports Concept 65 How should PHP code be tested? Quick recall Concept Glance Card 30 sec
01 Easy tipUnit-test rules; integration-test boundaries; exercise HTTP workflows. 02 Concise explanation“Use PHPUnit or Pest for focused behaviour, integration tests for databases and adapters, and feature tests for HTTP flows. Keep tests isolated, use representative fixtures, fake external services, and run the suite in CI.”
03 Memory formulaUnit + integration + feature + CI04 Real-world usesrefactoring regression prevention deployment confidence Concept 66 How should Composer dependencies be maintained? Quick recall Concept Glance Card 30 sec
01 Easy tipLock applications, audit often, update deliberately. 02 Concise explanation“Declare constraints in composer.json, commit composer.lock for applications, run composer install in CI and production, update dependencies deliberately, separate development tools, and use composer audit plus supported PHP versions.”
03 Memory formulaDeclare + lock + install + audit + update04 Real-world usessupply-chain security reproducible deploys package upgrades Concept 67 Which modern PHP features improve application design? Quick recall Concept Glance Card 30 sec
01 Easy tipUse language features to make invalid states harder to represent. 02 Concise explanation“Constructor promotion, readonly properties, enums, attributes, union and intersection types, named arguments, match, and the nullsafe operator improve contracts and reduce boilerplate when used deliberately.”
03 Memory formulaTypes + readonly + enums + match = clearer models04 Real-world usesDTOs domain values framework metadata Concept 68 What are attributes? Quick recall Concept Glance Card 30 sec
01 Easy tipStructured metadata read through reflection. 02 Concise explanation“Attributes attach machine-readable metadata to classes, methods, properties, parameters, and functions. Frameworks use them for routes, validation, mapping, and dependency configuration.”
03 Memory formula#[Metadata] + reflection = declarative configuration04 Real-world usesrouting ORM mapping validation Concept 69 What are enums and match expressions? Quick recall Concept Glance Card 30 sec
01 Easy tipEnums replace magic values; match returns strict results. 02 Concise explanation“Backed enums model finite sets with behaviour and parse untrusted strings through tryFrom(). match uses strict comparison, returns a value, and can expose unhandled cases more clearly than switch.”
03 Memory formulaEnum = valid set; match = strict expression04 Real-world usesstatuses permissions workflow states Concept 70 What are Fibers and JIT? Quick recall Concept Glance Card 30 sec
01 Easy tipFibers coordinate suspension; JIT may help CPU-heavy code. 02 Concise explanation“Fibers provide cooperative suspension primitives mainly used by async libraries. JIT can improve some CPU-heavy workloads but often offers limited benefit to I/O-bound CRUD applications, so measure before enabling.”
03 Memory formulaFibers = cooperative control; JIT = measured CPU optimisation04 Real-world usesasync libraries event loops specialised computation Concept 71 What is CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipA lightweight modern PHP framework with explicit tooling. 02 Concise explanation“CodeIgniter 4 provides routing, controllers, database tools, validation, caching, sessions, filters, security helpers, testing support, and the Spark CLI with namespaces and Composer-based conventions.”
03 Memory formulaCI4 = lightweight MVC + services + Spark04 Real-world usesweb applications REST APIs legacy migrations Concept 72 How is a CodeIgniter 4 project installed and configured? Quick recall Concept Glance Card 30 sec
01 Easy tipComposer starter, environment configuration, Spark commands. 02 Concise explanation“Create the official app starter with Composer, configure deployment values through .env or server settings, use php spark for local and operational commands, and keep secrets out of source control.”
03 Memory formulaComposer create + .env + php spark04 Real-world usesproject setup environment management deployment Concept 73 How do routing and controllers work in CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipExplicit method routes lead to thin controllers. 02 Concise explanation“Routes in app/Config/Routes.php map HTTP methods and URI patterns to controller actions. Prefer explicit routes; controllers parse requests, authorise, invoke application behaviour, and return responses rather than owning all business logic.”
03 Memory formulaRoute -> thin controller -> service -> response04 Real-world usesweb endpoints REST controllers security review Concept 74 How do models, Query Builder, and transactions work in CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipCompose bound queries and keep atomic work short. 02 Concise explanation“CI4 models and Query Builder provide data access, value binding, joins, and persistence. Query Builder does not make arbitrary raw expressions safe. Use short transactions for related changes and inspect plans for slow queries.”
03 Memory formulaModel/Builder + bound values + short transaction04 Real-world usesCRUD reporting data integrity Concept 75 How do services, libraries, helpers, and autoloading differ in CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipUse the smallest abstraction that makes dependencies explicit. 02 Concise explanation“PSR-4 and Composer load classes. Libraries are namespaced classes, services centralise shared construction, and helpers provide focused procedural functions. Prefer injected services when state or dependencies are involved.”
03 Memory formulaHelper = functions; library = class; service = shared construction04 Real-world usesapplication organisation dependency management CI3 migration Concept 76 How do filters, events, and legacy hooks differ? Quick recall Concept Glance Card 30 sec
01 Easy tipFilters wrap requests; events notify; hooks are CI3 legacy. 02 Concise explanation“CI4 filters handle request and response concerns such as authentication or CSRF. Events publish decoupled notifications. CI3 hooks modified execution points and should generally become filters or events during migration.”
03 Memory formulaRequest concern = filter; notification = event04 Real-world usesauthentication logging CI3 upgrades Concept 77 How are validation, CSRF, and authentication handled in CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipFramework controls help, but policy checks remain server-side. 02 Concise explanation“Use server-side validation rules, enable the CSRF filter for cookie-authenticated state changes, and prefer maintained authentication tooling such as CodeIgniter Shield. Enforce resource-level authorisation independently of hidden UI controls.”
03 Memory formulaValidate + CSRF + maintained auth + policy04 Real-world usesforms admin areas account security Concept 78 How are sessions, caching, and multiple instances handled in CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipChoose shared handlers before scaling out. 02 Concise explanation“Use the session and cache services with secure cookies, ID rotation, explicit cache keys and invalidation. Multiple application instances require shared session/cache handlers where state must be consistent.”
03 Memory formulaService + shared handler + explicit lifetime04 Real-world usesload-balanced apps login state performance Concept 79 How should CodeIgniter 4 handle uploads and email? Quick recall Concept Glance Card 30 sec
01 Easy tipValidate uploads synchronously; queue non-immediate email. 02 Concise explanation“Uploaded-file objects still need error, size, MIME, name, storage, execution, and authorisation controls. Configure email through environment-specific SMTP settings and queue delivery that need not block the response.”
03 Memory formulaSafe upload pipeline; configured and queued email04 Real-world usesmedia forms notifications background jobs Concept 80 How should CodeIgniter 4 REST APIs return data and errors? Quick recall Concept Glance Card 30 sec
01 Easy tipResponse objects provide consistent JSON and status codes. 02 Concise explanation“Define resource routes, validate input, use response objects for JSON and status codes, paginate collections, authenticate and authorise, and centralise production-safe error shapes.”
03 Memory formulaResource route + validation + response object04 Real-world usesmobile APIs SPA backends integrations Concept 81 How should CodeIgniter 4 integrate external APIs? Quick recall Concept Glance Card 30 sec
01 Easy tipUse the HTTP client with operational safeguards. 02 Concise explanation“Use CI4’s HTTP client or a maintained library with timeouts, TLS verification, authentication, status validation, bounded retries, observability, and SSRF protection for dynamic URLs.”
03 Memory formulaHTTP client + timeout + validation + safe retry04 Real-world usespayment APIs webhooks service calls Concept 82 How do migrations, environments, and deployment work in CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipVersion schema, externalise config, automate repeatably. 02 Concise explanation“Use migrations for schema changes, environment-specific configuration for deployment values, Spark commands for operational tasks, and repeatable CI/CD steps. Production credentials and keys stay outside the repository.”
03 Memory formulaMigration + environment config + automated deployment04 Real-world usesschema evolution CI/CD release safety Concept 83 How do you debug and test CodeIgniter 4? Quick recall Concept Glance Card 30 sec
01 Easy tipReproduce one request, trace it, then protect the fix with a test. 02 Concise explanation“Use structured logs, request IDs, the debug toolbar, database timing, PHPUnit-based tests, and Xdebug where appropriate. Display details locally, hide them in production, and test controllers, services, filters, and persistence at suitable layers.”
03 Memory formulaReproduce -> trace -> fix -> regression test04 Real-world usesincident diagnosis framework upgrades CI pipelines Concept 84 How does the cache-aside pattern work in PHP? Quick recall Concept Glance Card 30 sec
01 Easy tipRead the cache first; populate it only after a miss. 02 Concise explanation“With cache-aside, PHP checks Redis, Memcached, or another cache before loading from the source. On a miss it fetches the value, stores it with an appropriate TTL, and returns it; writes must update or invalidate affected keys.”
03 Memory formulaGet -> hit return; miss -> load -> cache -> return04 Real-world usesdatabase load reduction external API caching expensive computations Concept 85 How do you keep PHP cached data consistent after writes? Quick recall Concept Glance Card 30 sec
01 Easy tipCommit first, then update or invalidate every affected key. 02 Concise explanation“After the source of truth commits, invalidate dependent cache keys or replace them with committed values. Design keys around all query inputs, define acceptable staleness, and make distributed invalidation events retryable and idempotent.”
03 Memory formulaCommit source -> invalidate or update -> bounded staleness04 Real-world useswrite workflows derived queries multi-instance applications Concept 86 How should a PHP application handle cache failures? Quick recall Concept Glance Card 30 sec
01 Easy tipBound cache latency and choose fallback behavior deliberately. 02 Concise explanation“Use short timeouts, bounded retries, connection limits, and cache health metrics. Depending on the data, fall back to the source, serve stale content, shed load, or fail closed; uncontrolled database fallback can cause an outage cascade.”
03 Memory formulaBound wait -> fallback by policy -> protect source -> observe04 Real-world usesRedis outages latency control resilient applications