Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Interview Questions

PHP

Top 25 PHP Interview Questions

Curated questions covering PHP OOP, magic methods, PDO, sessions, closures, and PHP 8 features.

01

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 arguments.
  • print — outputs a single string; always returns 1; can be used in expressions.
  • Both are language constructs, not functions.
Example
<?php
echo "Hello", " ", "World"; // multiple args
$result = print("Hello");   // $result = 1
?>
02

What are the data types in PHP?

  • Scalar: int, float, string, bool
  • Compound: array, object
  • Special: null, resource
  • PHP 8 added union types (int|string) and the never return type.
03

What are the types of arrays in PHP?

  • Indexed array — numeric keys starting from 0.
  • Associative array — string keys.
  • Multidimensional array — arrays containing other arrays.
Example
<?php
$indexed = ["apple", "banana", "cherry"];
$assoc   = ["name" => "Alice", "age" => 25];
$multi   = [
    ["id" => 1, "name" => "Bob"],
    ["id" => 2, "name" => "Carol"],
];
echo $assoc["name"]; // Alice
?>
04

What is OOP in PHP? Explain classes and objects.

A class is a blueprint defining properties and methods. An object is an instance of a class. PHP supports all four OOP pillars: encapsulation, inheritance, polymorphism, and abstraction.

Example
<?php
class Animal {
    public string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
    public function speak(): string {
        return "...";
    }
}
class Dog extends Animal {
    public function speak(): string {
        return "Woof!";
    }
}
$dog = new Dog("Rex");
echo $dog->speak(); // Woof!
?>
05

What are traits in PHP?

Traits are a mechanism for code reuse in single-inheritance languages. A trait is like a partial class — it defines methods that can be included in multiple classes using the use keyword.

Example
<?php
trait Timestampable {
    public function getCreatedAt(): string {
        return date("Y-m-d H:i:s");
    }
}
class Post {
    use Timestampable;
}
$post = new Post();
echo $post->getCreatedAt();
?>
06

What are magic methods in PHP?

  • __construct() — called when an object is created.
  • __destruct() — called when an object is destroyed.
  • __get($name) / __set($name, $value) — called on inaccessible property access/assignment.
  • __toString() — called when an object is used as a string.
  • __call($name, $args) — called when invoking inaccessible methods.
Example
<?php
class Magic {
    private array $data = [];
    public function __set(string $k, mixed $v): void { $this->data[$k] = $v; }
    public function __get(string $k): mixed { return $this->data[$k] ?? null; }
    public function __toString(): string { return json_encode($this->data); }
}
$m = new Magic();
$m->name = "Alice";
echo $m->name;  // Alice
echo $m;        // {"name":"Alice"}
?>
07

What is the difference between abstract class and interface in PHP?

  • Abstract class — can have concrete methods, properties, and constructors. A class can extend only one abstract class.
  • Interface — only method signatures (PHP 8 allows constants). A class can implement multiple interfaces.
  • Use abstract class for shared implementation; use interface for defining a contract.
08

What are namespaces in PHP?

Namespaces prevent name collisions between classes, functions, and constants in large projects. They are declared at the top of a file with the namespace keyword.

Example
<?php
namespace App\Models;

class User {
    public string $name;
}

// In another file:
use App\Models\User;
$user = new User();
?>
09

What is Composer in PHP?

Composer is the dependency manager for PHP. It manages project dependencies declared in composer.json, downloads packages from Packagist, and generates an autoloader via vendor/autoload.php.

10

What is the difference between PDO and MySQLi?

  • PDO (PHP Data Objects) — database-agnostic; supports 12+ databases; object-oriented only; supports named parameters in prepared statements.
  • MySQLi — MySQL-specific; supports both OOP and procedural styles; slightly faster for MySQL-only projects.
  • PDO is generally preferred for portability.
Example
<?php
// PDO prepared statement
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(["id" => 1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
?>
11

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 multiple times with different parameters.

Example
<?php
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["Alice", "alice@example.com"]);
$stmt->execute(["Bob",   "bob@example.com"]);
?>
12

What is the difference between sessions and cookies in PHP?

  • Sessions — data stored on the server; identified by a session ID sent as a cookie; more secure for sensitive data.
  • Cookies — data stored in the browser; sent with every request; can persist across browser restarts; limited to ~4KB.
Example
<?php
// Session
session_start();
$_SESSION["user"] = "Alice";

// Cookie
setcookie("theme", "dark", time() + 86400, "/");
echo $_COOKIE["theme"] ?? "light";
?>
13

What is the difference between GET and POST in PHP?

  • GET — data sent in the URL query string; visible; cached; limited size (~2KB); used for retrieving data.
  • POST — data sent in the request body; not visible in URL; no size limit; used for submitting forms and sensitive data.
14

What is the difference between include and require in PHP?

  • include — if the file is not found, a warning is issued and execution continues.
  • require — if the file is not found, a fatal error is thrown and execution stops.
  • include_once / require_once — same as above but the file is included only once even if called multiple times.
15

How does error handling work in PHP?

PHP uses try/catch/finally blocks for exception handling. Custom exceptions extend the Exception class. set_error_handler() and set_exception_handler() allow global error handling.

Example
<?php
function divide(int $a, int $b): float {
    if ($b === 0) throw new InvalidArgumentException("Division by zero");
    return $a / $b;
}
try {
    echo divide(10, 0);
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
} finally {
    echo " Done.";
}
?>
16

What are closures in PHP?

Closures are anonymous functions that can capture variables from the enclosing scope using the use keyword.

Example
<?php
$multiplier = 3;
$multiply = function(int $n) use ($multiplier): int {
    return $n * $multiplier;
};
echo $multiply(5); // 15

$nums = [1, 2, 3, 4, 5];
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
?>
17

What are arrow functions in PHP 7.4+?

Arrow functions (fn) are a shorter syntax for closures. They automatically capture variables from the outer scope without needing use.

Example
<?php
$factor = 10;
$multiply = fn($n) => $n * $factor; // $factor captured automatically
echo $multiply(5); // 50
?>
18

What are type declarations in PHP?

PHP supports type declarations for function parameters, return types, and class properties. strict_types=1 enforces strict type checking.

Example
<?php
declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

class User {
    public function __construct(
        public readonly string $name,
        public int $age
    ) {}
}
?>
19

What is the null coalescing operator (??) in PHP?

The null coalescing operator returns the left operand if it exists and is not null; otherwise it returns the right operand. It is a cleaner alternative to isset() checks.

Example
<?php
$name = $_GET["name"] ?? "Guest";
$config["timeout"] ??= 30; // null coalescing assignment (PHP 7.4+)
echo $name;
?>
20

What is the spread operator in PHP?

The spread operator (...) unpacks an array into function arguments or merges arrays.

Example
<?php
function sum(int ...$nums): int {
    return array_sum($nums);
}
$numbers = [1, 2, 3];
echo sum(...$numbers); // 6

$a = [1, 2];
$b = [3, 4];
$merged = [...$a, ...$b]; // [1, 2, 3, 4]
?>
21

What is the match expression in PHP 8?

match is similar to switch but uses strict comparison (===), returns a value, and does not fall through. Each arm is a single expression.

Example
<?php
$status = 2;
$label = match($status) {
    1 => "Active",
    2 => "Inactive",
    3 => "Banned",
    default => "Unknown",
};
echo $label; // Inactive
?>
22

What are named arguments in PHP 8?

Named arguments allow passing values to a function by parameter name, making the order irrelevant and improving readability for functions with many optional parameters.

Example
<?php
function createUser(string $name, int $age = 18, bool $active = true): string {
    return "$name, $age, " . ($active ? "active" : "inactive");
}
echo createUser(age: 25, name: "Alice"); // Alice, 25, active
?>
23

What are fibers in PHP 8.1?

Fibers are lightweight coroutines that allow pausing and resuming execution. They provide a foundation for cooperative multitasking and async programming without callbacks.

Example
<?php
$fiber = new Fiber(function(): void {
    $value = Fiber::suspend("first");
    echo "Got: $value\n";
});
$result = $fiber->start();
echo $result . "\n"; // first
$fiber->resume("hello"); // Got: hello
?>
24

What are static methods and properties in PHP?

Static members belong to the class rather than any instance. They are accessed using the :: operator (scope resolution) and do not require object instantiation.

Example
<?php
class Counter {
    private static int $count = 0;
    public static function increment(): void { self::$count++; }
    public static function getCount(): int   { return self::$count; }
}
Counter::increment();
Counter::increment();
echo Counter::getCount(); // 2
?>
25

What is the difference between self, static, and parent in PHP?

  • self — refers to the class in which the method is defined; does not support late static binding.
  • static — refers to the class that was called at runtime (late static binding); useful in inheritance.
  • parent — refers to the parent class; used to call overridden parent methods.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.