44 PHP interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
PHP is a server-side scripting language used to build websites and web applications. Topics include language fundamentals, OOP, the type system including nullable types, newer language features such as match, security practices with PDO and password_hash, streams and I/O, OPcache and performance, SOLID in PHP, and Composer for dependency management.
PHP is a recursive acronym for PHP: Hypertext Preprocessor, meaning the first P stands for PHP itself. The name originally stood for Personal Home Page in the first versions of the 1990s, and was later changed to this recursive form. PHP is a server-side language…
Superglobals are pre-defined variables available everywhere in a script (including inside functions and methods) without declaring global. PHP populates them automatically on every request. The most important ones: - $GET: query string parameters from the URL (?page=2). - $POST: form data sent in the request…
Both collect form data but differ in where the data lives and how much you can send. - $GET reads from the URL query string, so the data is visible (http://example.com?name=John). URL length is limited by the browser and the web server (usually a few…
PHP has 8 core data types in 3 groups: 4 scalar types (hold a single value), 2 compound types (hold many values) and 2 special types. - Scalar: string, int, float, bool. - Compound: array (a list or key-value pairs), object (an instance of a…
Both are comparison operators but with different strictness. == checks if values are equal but allows type conversion. For example, "5" == 5 returns true because PHP converts the string to a number. The === (strict equal) checks both value AND type, so "5" ===…
Under the hood PHP has only one array type: an ordered map (key → value pairs that keep insertion order). The "three array types" people mention are just three ways of using it: - Indexed array: integer keys auto-assigned from 0, accessed by position: $fruits[0].…
Commonly used string functions: - strlen(): string length (in bytes; for UTF-8 text with accents use mbstrlen()). - strpos(): position of the first occurrence of a substring, false if not found. - strreplace(): replace text. - substr(): extract a portion of a string. - strtolower(),…
Both pull another PHP file into the running script. They differ in what happens when the file is not found. - include: raises a warning (EWARNING), returns false, and the script keeps running. - require: also raises the warning first, then stops the script with…
Access form data through superglobals: for GET use $GET['fieldname'], for POST use $POST['fieldname']. The rule is validate the raw input when it comes in, escape it when you output it: - Check it exists: $POST['email'] ?? '' (or isset()) avoids a warning when the field…
PHP has two error mechanisms: traditional errors (Notice, Warning, Fatal error) that are only printed or logged, and exceptions since PHP 7 that can be caught with try/catch. Traditional errors are split by severity: - Notice / Warning: the script keeps running. Examples: reading an…
Define constants with define("CONSTANTNAME", value) or const CONSTANTNAME = value;. Constants have no dollar sign, cannot be changed after definition, and are global without needing the global keyword. Since PHP 8.0, constants are always case-sensitive (the $caseinsensitive parameter of define() was removed). Use constants for…
A class is a blueprint: it defines which properties and methods an object will have. An object is a concrete instance created from that class with new. One class can create many objects. The two new calls create two independent objects. Each object has its…
Inheritance lets a child class receive properties and methods from a parent class, promoting code reuse. Use class Admin extends User to inherit. The child can access the parent's public and protected members (not private), override parent methods, add new functionality, and call the parent's…
PHP does not support multiple inheritance: a class can extends only one parent. To get a similar effect, PHP splits the job across two tools: interfaces for contracts (which methods a class must have) and traits for code reuse. Employee implements two interfaces at once,…
An interface is a contract: a list of methods (name, parameters, return type) that every class implementing it must have. An interface contains no implementation code. If InMemoryUserRepository misses a method of the interface, PHP raises a fatal error as soon as the class is…
Traits let you reuse methods in multiple unrelated classes without inheritance. PHP allows only one parent class, so when User and Product both need logging but share no parent, a trait is where that shared code goes. Think of traits as "horizontal" reuse versus inheritance's…
Magic methods are special methods (names starting with ) that PHP calls automatically in response to certain actions. Key ones: - construct(): runs when an object is created. - destruct(): runs when the object is destroyed. - get(): reading a property that does not exist…
An instance method belongs to an object, can use that object's own data through $this, and is called with $object-method(). A static method belongs to the class itself, has no $this, and is called with ClassName::method(). getName() needs to know "which user", so it must…
Access modifiers control visibility of properties and methods: public accessible everywhere (inside/outside class and subclasses), private accessible only inside that class (not subclasses), protected accessible inside class and subclasses but not outside. Example: private $password prevents direct access like $user-password = "hacked", forcing use of…
A readonly class (PHP 8.2) adds readonly to every declared property, whether public, protected or private, and forbids dynamic properties. Each property can be assigned only once, from inside the class; any later reassignment throws an Error: Constraints: - Every property must be typed (no…
An enum (PHP 8.1+) is a type with a fixed set of values. Each value is a single object of the enum, so comparison with === and match both work. Two kinds of enum: - Pure enum: only case names; no -value, no from()/tryFrom(), and…
md5/sha1 are fast, unsalted hashes → trivial to brute-force on a GPU and to reverse via rainbow tables. passwordhash() uses a deliberately slow algorithm (bcrypt by default, or Argon2) with a random salt embedded in the output string, so you never need a separate salt…
?T declares a value that is either type T or null. It works for parameters, return types, and properties (since 7.4). It is an explicit contract: ?int accepts int or null, but not a string. - Since PHP 8, ?T is equivalent to the union…
Five OOP design principles distilled by Robert C. Martin: - S — Single Responsibility: a class should have one reason to change. Keep email-sending logic out of the User class. - O — Open/Closed: open for extension, closed for modification. Add a new PayPalGateway class…
Composer is PHP’s per-project dependency manager (the role npm plays for Node). It resolves the dependency tree and generates an autoloader. - composer.json — declares packages and semver version constraints (^8.0, ~2.3). - composer.lock — pins the exact installed versions for reproducible builds. Commit it;…
Four differences worth naming: 1. Strict comparison. match uses ===, switch uses ==. This is the follow-up interviewers push on. 2. It is an expression. match returns a value, so you can assign or return it directly. switch is a statement. 3. No fall-through. No…
Constructor property promotion declares and assigns properties directly on constructor parameters, removing the private X $x; ... $this-x = $x; boilerplate. Named arguments pass parameters by name instead of by position: Benefits: calls with many boolean/null parameters become readable, and you can skip optional parameters…
In traditional PHP (PHP-FPM, modphp), each request starts with empty memory and every object is destroyed when it ends — so a Singleton is only "single" within one request. It cannot keep a connection, cache or state for the next request, which is exactly why…
isset($x) returns true when the variable exists and is not null. empty($x) returns true when the variable does not exist or its value is falsy — equivalent to !isset($x) $x == false. Both are language constructs and raise no warning for undefined variables. Value isset()…