PHP Interview Questions
Are you preparing for a PHP developer interview whether you're an experienced backend developer or just brushing up your skills, this guide brings you 100 hand-picked advanced PHP interview questions with clear explanations and real code examples. From object-oriented programming and traits to magic methods and dependency injection, learn everything you need to impress in your next technical round.
1. What is the difference between ==
and ===
in PHP?
Answer:
-
==
checks if values are equal, but not types. -
===
checks if values are equal and of the same type.
Example:
$a = 5; // integer $b = '5'; // string var_dump($a == $b); // true var_dump($a === $b); // false
Explanation:
$a == $b
is true because both are 5.
But $a === $b
is false because one is an integer and the other is a string.
2. What are traits in PHP and why are they used?
Answer:
Traits are like reusable chunks of code. PHP doesn't support multiple inheritance (a class extending two classes), but traits let you use methods from multiple sources.
Example:
trait Logger { public function log($msg) { echo "Log: $msg"; } } class MyClass { use Logger; } $obj = new MyClass(); $obj->log("Hello!");
Explanation:
Here, the Logger
trait gives the log()
method to MyClass
, without inheritance. You can reuse traits across many classes.
3. What is late static binding in PHP?
Answer:
Late static binding allows you to reference the called class, not the class where the method was originally defined.
Example:
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // late static binding
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test(); // Outputs: B
Explanation:
If we used self::who()
, it would print A
. But static::who()
refers to the calling class (B
), thanks to late static binding.
4. What are generators in PHP?
Answer:
Generators are like lightweight iterators. They help loop over data without loading everything into memory.
Example:
function countUpTo($n) { for ($i = 1; $i <= $n; $i++) { yield $i; } } foreach (countUpTo(5) as $num) { echo $num . " "; }
Explanation:
Instead of returning all values at once, yield
returns one value at a time. It’s memory efficient for large data sets.
5. What is the difference between public
, protected
, and private
in PHP?
Answer:
These are access modifiers for class members (properties or methods):
-
public
– accessible from anywhere. -
protected
– accessible only inside the class and its child classes. -
private
– accessible only inside the class itself.
Example:
class Test {
public $a = "Public";
protected $b = "Protected";
private $c = "Private";
public function show() {
echo $this->a . ", " . $this->b . ", " . $this->c;
}
}
$obj = new Test();
$obj->show(); // Works
echo $obj->a; // Works
// echo $obj->b; // Error
// echo $obj->c; // Error
Explanation:
You can access $a
from outside. $b
and $c
are protected/private, so direct access gives an error.
6. What is the use of final
keyword in PHP?
Answer:
The final
keyword prevents class or method from being overridden.
Example:
class A {
final public function hello() {
echo "Hello";
}
}
class B extends A {
// public function hello() {} // Error!
}
Explanation:
You can't override the hello()
method in class B
because it's marked final
.
7. What is the use of the __call()
magic method in PHP?
Answer:
__call()
is triggered when calling an undefined method in an object.
Example:
class Magic {
public function __call($name, $arguments) {
echo "Calling method '$name' with arguments: " . implode(', ', $arguments);
}
}
$obj = new Magic();
$obj->sayHello("World"); // sayHello is not defined
Explanation:
Even though sayHello
is not defined, __call()
catches it and handles the call gracefully.
8. How can you handle errors in PHP using try-catch?
Answer:
Use try-catch
to handle exceptions and avoid fatal errors.
Example:
try {
if (!file_exists("test.txt")) {
throw new Exception("File not found!");
}
} catch (Exception $e) {
echo "Caught error: " . $e->getMessage();
}
Explanation:
If test.txt
is missing, it throws an exception. The catch block handles it, preventing a crash.
9. What is Dependency Injection in PHP?
Answer:
Dependency Injection is a design pattern where a class gets its dependencies from outside, not by creating them itself.
Example:
class Logger {
public function log($msg) {
echo $msg;
}
}
class UserService {
private $logger;
public function __construct(Logger $logger) {
$this->logger = $logger;
}
public function createUser() {
$this->logger->log("User created!");
}
}
$logger = new Logger();
$service = new UserService($logger);
$service->createUser();
Explanation:
UserService
doesn’t create a Logger
. It receives it via the constructor. This makes testing and managing dependencies easier.
10. What is the difference between abstract class and interface in PHP?
Answer:
Abstract Class | Interface |
---|---|
Can have properties and methods | Can only have method signatures (until PHP 8) |
Can have both defined and undefined methods | Only method declarations (no body, except static methods in PHP 8+) |
Use abstract keyword |
Use interface keyword |
Supports inheritance | Supports multiple inheritance |
Example:
interface Shape {
public function getArea();
}
abstract class Polygon {
public function sayHi() {
echo "Hi from Polygon!";
}
}
class Rectangle extends Polygon implements Shape {
public function getArea() {
return 10 * 20;
}
}
Explanation:
-
Interface is like a contract.
-
Abstract class gives some shared functionality.
-
You can implement multiple interfaces but only extend one abstract class.
11. What is the difference between include, require, include_once, and require_once in PHP?
Answer:
These are used to include files in PHP, but they differ in error handling and repeat inclusion.
-
include
→ throws a warning if the file is not found. -
require
→ throws a fatal error and stops execution if the file is not found. -
include_once
/require_once
→ ensures the file is included only once.
Example:
include 'file.php'; // Warning if missing require 'file.php'; // Fatal error if missing include_once 'file.php'; // Included only once require_once 'file.php'; // Included only once
Explanation:
Use require
when the file is essential. Use include
for optional files.
12. What is the difference between static and non-static methods in PHP?
Answer:
-
Static methods can be called without creating an object.
-
Non-static methods require object instantiation.
Example:
class MyClass { public static function sayHi() { echo "Hi!"; } public function sayHello() { echo "Hello!"; } } MyClass::sayHi(); // Static method $obj = new MyClass(); $obj->sayHello(); // Non-static method
Explanation:
Static methods are used for utility-style functions that don’t depend on object state.
13. What is an anonymous function (closure) in PHP?
Answer:
An anonymous function is a function without a name, often used for short-lived operations or callbacks.
Example:
$greet = function($name) { return "Hello, $name!"; }; echo $greet("John");
Explanation:
Closures can be stored in variables, passed as parameters, and even use variables from outside using use
.
14. What is namespacing in PHP and why use it?
Answer:
Namespaces prevent class and function name collisions.
Example:
namespace App\Models; class User { public function getName() { return "John"; } } // Usage $user = new \App\Models\User();
Explanation:
Namespaces are essential for organizing code in large applications.
15. What is the SPL in PHP?
Answer:
SPL = Standard PHP Library. It provides a collection of interfaces and classes for common data structures (like LinkedList, Stack, etc).
Example:
$stack = new SplStack(); $stack->push("First"); $stack->push("Second"); echo $stack->pop(); // Second
Explanation:
SPL helps manage data structures without implementing them manually.
16. How do you use type declarations in PHP?
Answer:
Type declarations enforce variable types for function parameters and return types.
Example:
function add(int $a, int $b): int { return $a + $b; } echo add(5, 3); // Outputs: 8
Explanation:
This helps catch bugs early by ensuring the correct data types are used.
17. What is object cloning in PHP?
Answer:
Cloning creates a shallow copy of an object using the clone
keyword.
Example:
class MyClass { public $name = "Original"; } $a = new MyClass(); $b = clone $a; $b->name = "Cloned"; echo $a->name; // Original echo $b->name; // Cloned
Explanation:
Each object becomes independent after cloning.
18. What is the difference between isset(), empty(), and is_null()?
Answer:
-
isset()
→ checks if variable is set and not null. -
empty()
→ checks if variable is empty. -
is_null()
→ checks if variable is null.
Example:
$var = 0; var_dump(isset($var)); // true var_dump(empty($var)); // true var_dump(is_null($var)); // false
Explanation:
Use them according to what you're testing — existence, emptiness, or nullness.
examples, continuing in the same format:
19. What is the use of the __get()
and __set()
magic methods in PHP?
Answer:
These magic methods are triggered when accessing or assigning values to inaccessible (private/protected/non-existent) properties.
Example:
class Demo { private $data = []; public function __get($name) { return $this->data[$name] ?? "Not found"; } public function __set($name, $value) { $this->data[$name] = $value; } } $obj = new Demo(); $obj->name = "PHP"; echo $obj->name; // Output: PHP
Explanation:
They allow dynamic handling of properties and can be used for proxies or ORM models.
20. What is the difference between session and cookie in PHP?
Answer:
-
Session stores data on the server.
-
Cookie stores data in the user’s browser.
Example:
// Cookie setcookie("user", "John", time() + 3600); // Session session_start(); $_SESSION["user"] = "John";
Explanation:
Sessions are more secure; cookies are suitable for persistent lightweight data.
21. How does PHP handle references (&
) and what is their use?
Answer:
References allow two variables to point to the same data.
Example:
$a = "Hello"; $b = &$a; $b = "World"; echo $a; // Output: World
Explanation:
Useful when you want one variable to reflect changes in another, like passing by reference in functions.
22. What is the difference between unset() and null in PHP?
Answer:
-
unset()
destroys the variable. -
Setting a variable to
null
keeps it declared but with no value.
Example:
$a = "Hello"; unset($a); // $a is no longer set $b = "World"; $b = null; // $b is still set, but null
Explanation:
Use unset()
to remove variables completely.
23. What is the use of the yield from
expression in PHP?
Answer:
yield from
is used to delegate part of a generator to another generator.
Example:
function gen1() { yield 1; yield 2; } function gen2() { yield from gen1(); yield 3; } foreach (gen2() as $val) { echo $val . " "; // Output: 1 2 3 }
Explanation:
Makes code cleaner by reducing nested loops in generators.
24. What are weak references in PHP and when to use them?
Answer:
A weak reference allows referencing an object without preventing it from being garbage-collected.
Example:
$obj = new stdClass(); $weakRef = WeakReference::create($obj); unset($obj); var_dump($weakRef->get()); // NULL
Explanation:
Useful in caching systems where you don’t want to prevent object cleanup.
25. What is the purpose of array_map()
in PHP?
Answer:
array_map()
applies a callback to each element in one or more arrays.
Example:
$numbers = [1, 2, 3]; $squares = array_map(fn($n) => $n * $n, $numbers); print_r($squares); // [1, 4, 9]
Explanation:
It’s a functional approach to manipulating arrays.
26. How to create and use a custom exception in PHP?
Answer:
Extend the base Exception
class to define your own exception type.
Example:
class MyException extends Exception {} try { throw new MyException("Custom error!"); } catch (MyException $e) { echo $e->getMessage(); // Output: Custom error! }
Explanation:
Custom exceptions help categorize and handle specific error types.
27. What is the difference between explode() and str_split()?
Answer:
-
explode()
splits a string by a delimiter. -
str_split()
splits a string into chunks (by length).
Example:
$str = "a,b,c"; print_r(explode(",", $str)); // ['a', 'b', 'c'] $str2 = "hello"; print_r(str_split($str2, 2)); // ['he', 'll', 'o']
Explanation:
Use based on whether you're splitting by characters or delimiters.
28. What is the difference between foreach
and each()
in PHP?
Answer:
-
foreach
is a modern loop for arrays. -
each()
was used to return the current key-value pair and move the pointer (deprecated in PHP 7.2+).
Example (foreach):
$arr = ["a" => 1, "b" => 2]; foreach ($arr as $key => $value) { echo "$key => $value "; }
Explanation:
Avoid each()
in modern code; prefer foreach
for readability and compatibility.
29. What is a recursive function in PHP?
Answer:
A function that calls itself to solve smaller sub-problems.
Example:
function factorial($n) { return $n <= 1 ? 1 : $n * factorial($n - 1); } echo factorial(5); // Output: 120
Explanation:
Used in problems like factorial, tree traversal, etc.
30. What is the difference between array_merge() and array_merge_recursive()?
Answer:
-
array_merge()
overwrites values with the same key. -
array_merge_recursive()
merges them into arrays.
Example:
$a = ['color' => 'red']; $b = ['color' => 'blue']; print_r(array_merge($a, $b)); // ['color' => 'blue'] print_r(array_merge_recursive($a, $b)); // ['color' => ['red', 'blue']]
Explanation:
Use recursive merge when you want to retain all values.
31. How to serialize and unserialize data in PHP?
Answer:
Used to convert objects/arrays into a storable string format.
Example:
$data = ['name' => 'John']; $serialized = serialize($data); $unserialized = unserialize($serialized); print_r($unserialized);
Explanation:
Used in sessions, caching, or storing complex data structures.
31. What is the difference between array_filter()
and array_map()
?
Answer:
-
array_filter()
removes elements based on condition. -
array_map()
modifies each element.
Example:
$nums = [1, 2, 3, 4]; $even = array_filter($nums, fn($n) => $n % 2 === 0); // [2, 4] $squared = array_map(fn($n) => $n * $n, $nums); // [1, 4, 9, 16]
Explanation:
Filter = keep only what matches. Map = change values.
32. What is the difference between isset()
and empty()
in PHP?
Answer:
-
isset()
checks if a variable is set and notnull
. -
empty()
checks if a variable is empty (0
,''
,null
,false
, etc.)
Example:
$a = 0; var_dump(isset($a)); // true var_dump(empty($a)); // true
Explanation:
isset()
won’t return false for falsy values like 0, while empty()
will.
33. What is the Null Coalescing Operator (??
) in PHP?
Answer:
It returns the first operand if it's set and not null; otherwise, returns the second.
Example:
$name = $_GET['name'] ?? 'Guest'; echo $name;
Explanation:
It’s a shorthand for isset($var) ? $var : default
.
34. How to prevent SQL Injection in PHP?
Answer:
Use prepared statements with parameter binding.
Example (PDO):
$pdo = new PDO($dsn, $user, $pass); $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]);
Explanation:
Prepared statements ensure user input is properly escaped, preventing injection.
35. What is the difference between include
, require
, include_once
, and require_once
?
Answer:
-
include
gives a warning if the file is missing, script continues. -
require
gives a fatal error, script stops. -
_once
ensures the file is included only once.
Example:
include 'file.php'; require 'file.php'; include_once 'file.php'; require_once 'file.php';
Explanation:
Use require_once
for essential files to avoid multiple inclusions.
36. What is overloading and overriding in PHP OOP?
Answer:
-
Overloading: Using magic methods (
__get
,__set
,__call
) to dynamically create properties/methods. -
Overriding: Redefining a parent class method in a child class.
Example (Overriding):
class A { public function greet() { echo "Hello"; } } class B extends A { public function greet() { echo "Hi"; } } $obj = new B(); $obj->greet(); // Hi
Explanation:
Overriding customizes base class behavior, while overloading adds dynamic flexibility.
37. What are anonymous classes in PHP?
Answer:
Anonymous classes are one-off class definitions used when you don't need to reuse them.
Example:
$greeting = new class { public function say() { return "Hello from anonymous class!"; } }; echo $greeting->say();
Explanation:
Anonymous classes help when you need a simple class implementation without naming or reuse.
38. What is the difference between explode()
and str_split()
in PHP?
Answer:
-
explode()
splits a string by a delimiter into an array. -
str_split()
splits a string into individual characters or chunks of specified length.
Example:
$str = "Hello,World"; print_r(explode(",", $str)); // ['Hello', 'World'] print_r(str_split($str, 2)); // ['He', 'll', 'o,', 'Wo', 'rl', 'd']
Explanation:
Use explode()
when breaking a string by a known separator. Use str_split()
for character-level operations.
39. What is array_walk()
in PHP?
Answer:
array_walk()
applies a user-defined function to every element of an array.
Example:
$arr = [1, 2, 3]; array_walk($arr, function (&$value, $key) { $value *= 2; }); print_r($arr); // [2, 4, 6]
Explanation:
Useful for applying transformations with reference access to each value.
40. What is a Closure in PHP?
Answer:
A Closure is an anonymous function that can capture variables from the parent scope.
Example:
$multiplier = 3; $multiply = function ($n) use ($multiplier) { return $n * $multiplier; }; echo $multiply(5); // 15
Explanation:
Closures are commonly used in callbacks, array functions, and functional programming.
41. How does PHP handle timezones and date formatting?
Answer:
PHP uses the DateTime
class and date_default_timezone_set()
for timezones.
Example:
date_default_timezone_set('Asia/Kolkata'); $dt = new DateTime(); echo $dt->format('Y-m-d H:i:s');
Explanation:
Using DateTime
gives you timezone-aware, formatted, and manipulable date/time values.
42. What is the difference between unset()
and null
assignment in PHP?
Answer:
-
unset()
destroys the variable. -
Assigning
null
just empties its value.
Example:
$a = 5; unset($a); // Variable is removed $b = 5; $b = null; // Variable still exists, value is null
Explanation:
isset($a)
will return false after unset()
, but true for a variable set to null
.
43. What are callable types in PHP?
Answer:
Callable types are functions/methods passed as variables, closures, or arrays.
Example:
function greet($name) { return "Hello, $name"; } $call = 'greet'; echo $call('John'); // Hello, John
Explanation:
Useful for callbacks, array functions, and flexible APIs.
44. How do you make a class iterable in PHP?
Answer:
Implement the Iterator
or IteratorAggregate
interface.
Example:
class MyList implements IteratorAggregate { private $items = [1, 2, 3]; public function getIterator(): Traversable { return new ArrayIterator($this->items); } } $obj = new MyList(); foreach ($obj as $item) { echo $item . " "; }
Explanation:
This allows your objects to be used in foreach
just like arrays.
45. What is __autoload()
and how is it replaced in modern PHP?
Answer:
-
__autoload()
is an old method for loading undefined classes automatically. -
Replaced by
spl_autoload_register()
in modern PHP.
Example:
spl_autoload_register(function ($class) { include "classes/$class.php"; });
Explanation:
Modern autoloading allows registering multiple loaders and is compatible with Composer and PSR standards.
46. How do you handle large file uploads in PHP?
Answer:
-
Update
php.ini
:-
upload_max_filesize
-
post_max_size
-
max_execution_time
-
-
Use chunked uploads or background processing for huge files.
Explanation:
PHP has built-in limits for safety. For large files, it's common to handle chunks and optimize memory usage.
47. What is the use of __toString()
magic method in PHP?
Answer:
Allows an object to be treated as a string.
Example:
class Book { public $title = "PHP Guide"; public function __toString() { return $this->title; } } $book = new Book(); echo $book; // Output: PHP Guide
Explanation:
When an object is used in a string context, __toString()
is automatically called.