Top 25 PHP Interview Questions
Curated questions covering OOP, sessions, databases, security, Composer, and modern PHP features.
What is PHP and what are its key features?
PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. Key features: embedded in HTML, extensive database support, cross-platform, large ecosystem (Laravel, Symfony, WordPress), and easy deployment.
What is the difference between echo and print in PHP?
- echo — outputs one or more strings; no return value; slightly faster; can take multiple comma-separated values.
- print — outputs a string; returns 1; can be used in expressions.
- Both are language constructs, not functions.
What is the difference between == and === in PHP?
== compares values with type coercion ("1" == 1 is true). === compares both value and type without coercion ("1" === 1 is false). Always prefer === to avoid unexpected type juggling bugs.
What are PHP data types?
- Scalar: int, float, string, bool
- Compound: array, object
- Special: null, resource
- PHP is dynamically typed — variables can change type.
What is the difference between include, require, include_once, and require_once?
- include — includes a file; emits a warning if not found; execution continues.
- require — includes a file; emits a fatal error if not found; execution stops.
- include_once / require_once — same as above but only includes the file once even if called multiple times.
What are PHP sessions and cookies?
- Sessions — store data on the server; identified by a session ID stored in a cookie or URL. Use session_start() to begin.
- Cookies — store data on the client browser; sent with every HTTP request; can have expiry, path, and domain.
session_start();
$_SESSION["user"] = "Alice";
setcookie("theme", "dark", time() + 86400, "/");
What is OOP in PHP?
PHP supports object-oriented programming with classes, objects, inheritance, interfaces, traits, abstract classes, and access modifiers (public, protected, private).
class Animal {
protected string $name;
public function __construct(string $name) { $this->name = $name; }
public function speak(): string { return "..."; }
}
class Dog extends Animal {
public function speak(): string { return "{$this->name} says Woof!"; }
}
What are PHP traits?
Traits are a mechanism for code reuse in single-inheritance languages. A trait is like a partial class that can be included in multiple classes using the use keyword.
trait Timestampable {
public function getCreatedAt(): string { return date("Y-m-d"); }
}
class Post {
use Timestampable;
}
What is the difference between abstract class and interface in PHP?
- Abstract class — can have implemented methods and properties; a class can extend only one abstract class.
- Interface — only method signatures (no implementation); a class can implement multiple interfaces.
- Use interfaces for contracts; abstract classes for shared base implementation.
What are PHP magic methods?
Magic methods are special methods with double underscores. Common ones: __construct (constructor), __destruct (destructor), __get/__set (property access), __call (undefined method), __toString (string conversion), __clone (cloning).
What is PDO in PHP?
PDO (PHP Data Objects) is a database abstraction layer that provides a consistent interface for multiple databases. It supports prepared statements, which prevent SQL injection.
$pdo = new PDO("mysql:host=localhost;dbname=mydb", $user, $pass);
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(["id" => $id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
What are prepared statements and why are they important?
Prepared statements separate SQL code from data, preventing SQL injection attacks. The query is compiled once and executed with different parameters. Always use prepared statements for user-supplied data.
What is Composer in PHP?
Composer is PHP's dependency manager. It manages project dependencies via composer.json, autoloads classes via PSR-4, and installs packages from Packagist. Essential for modern PHP development.
// composer.json
{
"require": {
"monolog/monolog": "^3.0"
}
}
// composer install
// use autoloader
require "vendor/autoload.php";
What is the difference between GET and POST in PHP?
- GET — data in URL query string; visible; limited size (~2KB); cached; use for retrieving data.
- POST — data in request body; not visible in URL; no size limit; not cached; use for submitting data.
- Access via $_GET and $_POST superglobals.
What are PHP superglobals?
Superglobals are built-in variables accessible from any scope: $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_ENV, $GLOBALS.
What is the difference between isset() and empty()?
- isset() — returns true if variable exists and is not null.
- empty() — returns true if variable is falsy: "", 0, "0", null, false, [], or unset variable.
- Use isset() to check existence; empty() to check for meaningful value.
What is PHP namespacing?
Namespaces organise code and prevent naming conflicts between classes, functions, and constants. Declared with namespace keyword at the top of a file.
namespace App\Controllers;
use App\Models\User;
class UserController {
public function index(): array {
return User::all();
}
}
What are PHP closures?
Closures are anonymous functions that can capture variables from the enclosing scope using the use keyword.
$multiplier = 3;
$multiply = function(int $n) use ($multiplier): int {
return $n * $multiplier;
};
echo $multiply(5); // 15
What is the difference between array_map, array_filter, and array_reduce?
- array_map — applies a callback to each element; returns new array.
- array_filter — returns elements where callback returns true.
- array_reduce — reduces array to a single value using a callback.
$nums = [1, 2, 3, 4, 5];
array_map(fn($n) => $n * 2, $nums); // [2,4,6,8,10]
array_filter($nums, fn($n) => $n % 2 === 0); // [2,4]
array_reduce($nums, fn($c, $n) => $c + $n, 0); // 15
What is XSS and how do you prevent it in PHP?
XSS (Cross-Site Scripting) injects malicious scripts into web pages. Prevent it by escaping output with htmlspecialchars() or htmlentities() before rendering user data in HTML.
echo htmlspecialchars($userInput, ENT_QUOTES, "UTF-8");
What is CSRF and how do you prevent it?
CSRF (Cross-Site Request Forgery) tricks users into submitting unintended requests. Prevent it with CSRF tokens — generate a unique token per session, include it in forms, and validate it on submission.
What are PHP generators?
Generators use yield to produce values lazily, one at a time, without building the entire array in memory. Useful for large datasets.
function readLines(string $file): Generator {
$handle = fopen($file, "r");
while (($line = fgets($handle)) !== false) {
yield $line;
}
fclose($handle);
}
What is the difference between static and non-static methods?
Static methods belong to the class, not an instance. Called with ClassName::method(). They cannot access $this. Non-static methods belong to an instance and can access instance properties via $this.
What are PHP 8 features?
- Named arguments: func(name: "Alice", age: 25)
- Match expression — like switch but returns a value and uses strict comparison.
- Nullsafe operator: $user?->getAddress()?->city
- Union types: int|string
- Attributes (annotations): #[Route("/home")]
- Constructor property promotion.
What is the difference between array() and [] syntax?
Both create arrays. [] is the short array syntax introduced in PHP 5.4 and is the modern preferred style. array() is the older verbose syntax. They are functionally identical.