Top 50 PHP Web Development Interview Questions and Answers by OM IT Trainings Institute
Introduction
Preparing for a PHP Web Development interview? This comprehensive guide on Top 50 PHP Web Development Interview Questions and Answers by OM IT Trainings Institute is designed to help both beginners and experienced developers master essential PHP concepts, frameworks, database integration, and real-world web development practices. Whether you’re preparing for roles like PHP Developer, Web Developer, Backend Developer, or Full Stack Developer, this guide will help you strengthen your technical foundation and build the confidence to crack your interview.
Let’s explore the most important PHP Web Development Interview Questions and Answers to help you succeed.
So, let’s dive into this comprehensive collection of PHP Web Development Technical Interview Questions and Answers, carefully categorised by OM IT Trainings Institute to support your interview preparation journey:
PHP Web Development Interview Questions and Answers for Freshers
PHP Web Development Interview Questions and Answers for Experienced
1. What is PHP?
Answer: PHP (Hypertext Preprocessor) is a high-level, server-side scripting language used to develop dynamic websites and web applications. It is widely used for web development, content management systems, e-commerce platforms, and backend application development.
2. What are the key features of PHP?
Answer:
Open Source: Free to use and widely supported by the community.
Server-Side Scripting: Executes on the server and generates dynamic content.
- Platform Independent: Runs on Windows, Linux, and macOS.
- Database Support: Supports MySQL, PostgreSQL, Oracle, and more.
- Easy to Learn: Simple syntax, beginner-friendly.
- Flexible: Can be embedded within HTML.
- Secure: Offers features to protect against common web vulnerabilities.
- High Performance: Fast execution for web applications.
3. Explain PHP, MySQLi, and PDO.
Answer:
- PHP: A server-side scripting language used to build dynamic web applications.
- MySQLi (MySQL Improved): An extension in PHP used to connect and interact with MySQL databases.
- PDO (PHP Data Objects): A database abstraction layer that allows secure and flexible database connections with support for multiple databases.
4. How is PHP platform-independent?
Answer: PHP runs on the server and is supported by most web servers like Apache and Nginx. Since it is server-side, it can run on different operating systems (Windows, Linux, macOS) without changing the code, making it platform-independent.
5. What is the difference between a Class and an Object in PHP?
Answer:
- Class: A blueprint or template used to define properties (variables) and methods (functions). It defines the structure and behavior of objects.
- Object: An instance of a class. It represents a real entity created from the class and occupies memory when instantiated.
<?php
class Dog {
public $name;
public function bark() {
echo $this->name . " says Woof!";
}
}
$myDog = new Dog();
$myDog->name = "Buddy";
$myDog->bark();
echo "<br>";
$yourDog = new Dog();
$yourDog->name = "Lucy";
$yourDog->bark();
?>
Learn via our Course
PHP Web Development Training in Chandigarh & Mohali!
6. What are Data Types in PHP?
Answer: Basic data types that store values directly in variables. PHP has several built-in types: int, float, string, bool, array, object, NULL.
<?php $age = 25; // Integer number
$price = 99.99; // Decimal number
$isActive = true; // True/False value
$initial = "J"; // Single character $name = "Alice"; // String value echo
"Age: " . $age . "<br>"; echo "Price: " . $price . "<br>";
echo "Active: " . $isActive . "<br>";
echo "Initial: " . $initial . "<br>"; echo "Name: " . $name; ?> 7.What is the main file in PHP?
Answer: It’s the starting point for a PHP web application. The web server executes this file first when a user accesses the website.
- Common Example:
index.php
- Common Example:
<?php get_header(); if (have_posts()) : while (have_posts()) : the_post(); the_title(); the_content(); endwhile; else : echo "No posts found."; endif; get_footer(); ?>
8. What is a Constructor in PHP?
Answer: A special method used to initialize new objects. It is automatically called when an object of a class is created.
Syntax: __construct()
Types:
- Default (no parameters)
- Parameterized (takes parameters)
<?php class Person
{ public $name; public $age; public function __construct($personName = "Default Name", $personAge = 0)
{ $this->name = $personName; $this->age = $personAge; echo "Person created: " . $this->name . "<br>"; } }
$p1 = new Person("Bob", 30);
echo $p1->name . ", " . $p1->age . "<br>"; $p2 = new Person();
echo $p2->name . ", " . $p2->age; ?> 9. What is the difference between == and === in PHP?
Answer:
==: Compares values only (type juggling allowed).===: Compares both value and data type (strict comparison).
<?php
$age = 25; // Integer number
$price = 99.99; // Decimal number
$isActive = true; // True/False value
$initial = "J"; // Single character
$name = "Alice"; // String value
echo "Age: " . $age . "<br>";
echo "Price: " . $price . "<br>";
echo "Active: " . $isActive . "<br>";
echo "Initial: " . $initial . "<br>";
echo "Name: " . $name;
?>
Object-Oriented Programming (OOP) Concepts:
10. What is OOP? What are its four main principles?
Answer:OOP is a programming style based on “objects” which combine data and methods. Its main principles in PHP are:
- Encapsulation: Hiding data and showing only necessary methods (like a black box).
- Inheritance: A class can get features from another class (code reuse).
- Polymorphism: An object can take on many forms (doing different things based on context).
- Abstraction: Hiding complex details, showing only essential information.
<?php try
{ $a = 5 / 0; } catch (DivisionByZeroError $e)
{ echo "Cannot divide by zero"; }
finally
{ echo "<br>This will always run"; }
?>
11. Explain Inheritance in PHP with an example.
Answer: Inheritance allows a new class (subclass/child) to reuse properties and methods from an existing class (superclass/parent).
// Superclass (Parent)
class Vehicle {
function drive() {
echo "Vehicle is driving.";
}
}
// Subclass (Child) inheriting from Vehicle
class Car extends Vehicle { // 'extends' keyword
function honk() {
echo "Car says Beep beep!";
}
}
$myCar = new Car();
$myCar->drive(); // Inherited from Vehicle
$myCar->honk(); // Specific to Car
12. What is Method Overloading?
Answer: Having multiple methods with the same name in the same class, but with different types or numbers of parameters. This is compile-time polymorphism.
class Calculator {
int add(int a, int b) { // Method 1: two integers
return a + b;
}
double add(double a, double b) { // Method 2: two doubles
return a + b;
}
int add(int a, int b, int c) { // Method 3: three integers
return a + b + c;
}
}
public class OverloadingDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Calls add(int, int)
System.out.println(calc.add(5.5, 10.5)); // Calls add(double, double)
System.out.println(calc.add(1, 2, 3)); // Calls add(int, int, int)
}
}
13. What is Method Overloading?
Answer:
Having multiple methods with the same name in the same class, but with different types or numbers of parameters. This is compile-time polymorphism.
addInt(5, 10) . "
"; // Calls addInt
echo $calc->addDouble(5.5, 10.5) . "
"; // Calls addDouble
echo $calc->addThree(1, 2, 3) . "
"; // Calls addThree
?>
14. What is Abstraction in Java? How is it achieved?
Answer: Abstraction in PHP is hiding complex implementation details and showing only the necessary features to the user. It focuses on what an object does, not how it does it.
- Achieved by:
- Abstract Classes: Classes that cannot be instantiated and may contain abstract methods (methods without an implementation). Subclasses must provide implementations for these.
- Interfaces:Blueprints of a class that define a contract (methods without implementation). Classes implement interfaces.
abstract class Shape {
// Abstract method
abstract protected function calculateArea();
// Concrete method
public function display() {
echo "This is a shape.";
}
}
class Circle extends Shape {
protected $radius;
public function __construct($r) {
$this->radius = $r;
}
// Implementing the abstract method
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
// Interface define karna
interface Drivable {
public function start(); // Methods ka sirf naam (no body)
public function stop();
}
// Interface ko implement karna
class Car implements Drivable {
public function start() {
echo "Car engine started.";
}
public function stop() {
echo "Car engine stopped.";
}
}
// Object banakar check karna
$myCar = new Car();
$myCar->start();
$myCar->stop();
15. What is Encapsulation in PHP?
Answer: Encapsulation is bundling data (variables) and methods that operate on the data within a single unit (class). It also involves hiding the internal state of an object and exposing controlled access through public methods (getters and setters).
class BankAccount {
private float $balance; // Data is private (hidden)
public function __construct(float $initialBalance) {
if ($initialBalance >= 0) {
$this->balance = $initialBalance;
} else {
$this->balance = 0; // Controlled initialization
}
}
// Public getter to read balance
public function getBalance(): float {
return $this->balance;
}
// Public method to deposit (controlled modification)
public function deposit(float $amount): void {
if ($amount > 0) {
$this->balance += $amount;
} else {
echo "Deposit amount must be positive.\n";
}
}
}
// Usage:
$account = new BankAccount(1000);
$account->deposit(500);
echo "Current Balance: " . $account->getBalance();
16. What are Access Modifiers in PHP?
Answer: Keywords that control the visibility and accessibility of classes, properties (variables), and methods.
- public: Accessible from anywhere (inside the class, outside the class, or from child classes).
- protected: Accessible only within the class itself and by classes derived from that class (subclasses).
- private: Accessible only within the specific class where it is declared. Child classes cannot access private members of a parent.
String and Array Concepts:
17. What is a String in PHP? Is String mutable or immutable?
Answer:A String in Java is a sequence of characters. It is immutable, meaning its content cannot be changed after creation. Any “modification” creates a new String object.
// 1. Basic Concatenation (using the dot '.' operator) $s1 = "Hello"; $s2 = $s1 . " World"; // $s1 remains "Hello", $s2 is "Hello World" echo $s1 . "\n"; // Output: Hello echo $s2 . "\n"; // Output: Hello World // 2. Mutability Example (Changing a character) $s3 = "Jello"; $s3[0] = "H"; // Directly changing the first character echo $s3; // Output: Hello
18. What is the String Pool?
Answer: A special memory area in the Heap where String literals are stored and reused to save memory. When you create a String with a literal, Java checks the pool first.
// 1. Basic Concatenation (using the dot '.' operator) $s1 = "Hello"; $s2 = $s1 . " World"; // $s1 remains "Hello", $s2 is "Hello World" echo $s1 . "\n"; // Output: Hello echo $s2 . "\n"; // Output: Hello World // 2. Mutability Example (Changing a character) $s3 = "Jello"; $s3[0] = "H"; // Directly changing the first character echo $s3; // Output: Hello
19.Difference between String and Buffer Handling in PHP
Answer:
- String: The default way to handle text. In PHP, strings are highly optimized; you simply use the
.operator to append text. - Concatenation (The “StringBuilder” way): While PHP doesn’t have a specific class, using the
.or.=operator on a variable is the standard way to perform “StringBuilder” tasks. - Memory/Performance: For extremely large string manipulations (like building a massive HTML table), developers sometimes use an Array as a buffer and then
implode()it at the end for better performance.
// 1. Standard String (Immutable-like behavior, but flexible)
$str = "fixed";
$str = $str . " content"; // Original $str is replaced
// 2. StringBuilder Logic (Standard PHP approach)
$sb = "dynamic";
$sb .= " and fast"; // Using .= is the standard way to append
// 3. Manual "Buffer" (Best for very large loops/heavy data)
// Instead of StringBuffer, we use an array to collect parts
$buffer = [];
$buffer[] = "synchronized";
$buffer[] = " and safe";
$finalString = implode("", $buffer); // Combining at once is memory efficient
echo $sb . "\n";
echo $finalString;
20. What is an Array in PHP?
Answer: A flexible data structure that acts as both a list (indexed) and a map (associative). Unlike Java, you don’t need to specify a fixed size or a single data type upon creation.
// 1. Declare and initialize an indexed array (Auto-initialized) $numbers = array(); // Or more commonly: $numbers = []; $numbers[0] = 10; // Assign value // 2. Declare and initialize with values directly (Short syntax) $fruits = ["Apple", "Banana", "Cherry"]; // 3. Dynamic sizing (No need to define size like 'new int[5]') $numbers[] = 20; // Automatically adds 20 to index [1] echo $numbers[0]; // Output: 10 echo count($fruits); // Output: 3 (PHP uses count() instead of .length)
Exception Handling:
21. What is Exception Handling in PHP?
Answer: It is a mechanism to handle runtime errors or unexpected conditions (exceptions) that could otherwise stop the execution of a script. By “catching” these exceptions, you can provide a fallback, log the error, or show a user-friendly message instead of a “Fatal Error.”
22. Does PHP have Checked and Unchecked Exceptions?
Answer: Exceptions. You can choose to catch them, but the language won’t stop you from running the code if you don’t. However, modern PHP development (especially with tools like PHPStan or Psalm) encourages developers to treat certain errors as if they were “checked” for better code quality.
// 1. Handling a "Logic" Exception (Similar to Unchecked)
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Cannot divide by zero! \n";
}
// 2. Handling a "Runtime" Exception (Similar to Checked)
// PHP won't force you to catch this, but it's good practice
try {
if (!file_exists("nonexistent.txt")) {
throw new Exception("File not found!");
}
$file = fopen("nonexistent.txt", "r");
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
23. Explain try-catch-finally block in PHP
Answer:
- try: Encloses the code that might throw an exception or an error.
- catch: Catches and handles a specific exception if one is thrown inside the
tryblock. - finally: Always executes, regardless of whether an exception occurred or was caught (typically used for cleanup tasks like closing database connections).
try {
$arr = [1];
// In PHP, this might throw a 'TypeError' or 'Exception' depending on usage,
// but we can catch it using Throwable for safety.
if (!isset($arr[1])) {
throw new Exception("Index 1 is out of bounds.");
}
echo $arr[1];
} catch (Exception $e) {
// Catches the specific Exception thrown above
echo "Error: " . $e->getMessage();
} finally {
// This block always runs
echo "\nCleanup operations here.";
}
Other Important Concepts:
24. What is the static keyword in PHP?
Answer: static members (properties and methods) belong to the class. They are shared across all instances of the class, meaning if you change a static property in one place, it changes for everyone. You access them using the Scope Resolution Operator (::) instead of the arrow (->) operator.
class Counter {
public static $count = 0; // Shared by all instances
public $id;
public function __construct($id) {
$this->id = $id;
// Use self:: to access static property inside the class
self::$count++;
}
public static function displayCount() { // Class method
echo "Total counters: " . self::$count;
}
}
// Usage:
$c1 = new Counter("A");
$c2 = new Counter("B");
// Accessing static method using the Class Name and '::'
Counter::displayCount(); // Output: Total counters: 2
25. What is the difference between $this and parent in PHP?
Answer:
- this: Refers to the current object instance. It is used to access the properties and methods of the specific object you are working with.
- super: Refers to the parent class. It is used to access the parent’s methods or constants, especially when they have been overridden in the child class.
class Parent { int value = 10; }
class Child extends Parent {
int value = 20;
void showValues() {
System.out.println("Child's value (this.value): " + this.value);
System.out.println("Parent's value (super.value): " + super.value);
}
void callParentMethod() {
super.equals(this); // Example of calling parent's method
}
}
// In main:
// Child c = new Child();
// c.showValues();
26. What is a Namespace in PHP?
Answer: A way to encapsulate items such as classes, interfaces, functions, and constants into logical groups. They are used for:
- Organization: Structuring large projects by grouping related classes together.
- Naming Collision: Preventing name clashes between classes. (e.g., You can have two classes named
Userif they are in different namespaces). - Access Control: Making it clear which part of the application a class belongs to (e.g.,
App\ControllervsApp\Model).
27. Do Wrapper Classes exist in PHP?
Answer: No, PHP does not have dedicated Wrapper Classes like Java’s Integer or Boolean. In PHP, a variable can hold an integer, a string, or an object interchangeably. PHP handles the conversion between “primitive-like” values and their usage automatically behind the scenes.
28. Explain Autoboxing and Unboxing in PHP
Answer:
Since PHP doesn’t have wrapper objects for primitives, it doesn’t need “Autoboxing.” Instead, PHP uses a concept called Type Juggling.
- Type Juggling: PHP automatically converts a variable from one type to another based on the context (e.g., adding a string to an integer).
- Type Casting: This is the manual version (similar to Unboxing logic), where you force a variable to be a certain type.
29. Can we declare pointers in PHP?
Answer: No, PHP does not have explicit pointers like C or C++. Just like Java, this is a design choice to ensure security and simplify development. PHP uses References, which allow two variables to refer to the same content, but these are managed internally by the PHP engine and do not provide direct memory address access.
30. What is Garbage Collection in PHP?
Answer: PHP uses an automatic memory management system. It primarily uses Reference Counting and a Cycle Collector to reclaim memory. When a variable’s reference count reaches zero (meaning no part of the script is using it anymore), PHP automatically clears it from memory to prevent leaks
class MyObject {
public $name;
public function __construct($n) {
$this->name = $n;
}
// Destructor: Equivalent to Java's lifecycle management
public function __destruct() {
echo "MyObject " . $this->name . " is being cleared from memory.\n";
}
}
// 1. Create an object
$obj = new MyObject("Temp");
// 2. Remove the reference
$obj = null; // This makes the "Temp" object eligible for Garbage Collection
// 3. Manual trigger (Rarely needed, similar to System.gc())
gc_collect_cycles();
echo "End of script.";
Java Interview Questions and Answers for Experienced
31. Explain the PHP Memory Model and Request Lifecycle.
Answer:
Unlike Java’s JMM, PHP uses a Shared-Nothing Architecture. Each HTTP request is independent with its own memory space.
Request Lifecycle: When a request hits the server (FPM/Apache), PHP allocates memory, executes the script, and then flushes almost everything.
Importance: Because memory is wiped after each request, you don’t typically worry about thread-safe visibility of variables. However, for long-running CLI tasks or using extensions like Swoole or Parallel, understanding memory allocation and garbage collection is vital to prevent memory leaks.
32. Fail-Fast vs. Fail-Safe in PHP.
Answer:PHP doesn’t have explicit “Fail-Safe” iterators in the core library because it is single-threaded.
Fail-Fast behavior: If you modify an array while using a
foreachloop, PHP’s internal pointer might behave unpredictably. In many cases, PHP works on a copy of the array (copy-on-write), but if you iterate by reference (foreach ($arr as &$val)), structural changes can lead to logical errors.PHP “Fail-Safe”: To achieve “Fail-Safe” behavior, developers manually create a copy using
array_values($data)or use anArrayIteratorobject.
33. Abstract Class vs. Interface in PHP.
Answer:
Abstract Class: Use when you have a “is-a” relationship and want to share concrete code (methods with logic) and properties across child classes. (e.g.,
BaseControllerproviding arender()method).Interface: Use to define a contract (“can-do” relationship) for unrelated classes. PHP supports multiple interfaces but only single inheritance. Interfaces are crucial for Dependency Injection and decoupling.
34. Immutability in PHP.
Answer: PHP objects are mutable by default. Immutability is achieved by:
Making properties
readonly(PHP 8.1+).Using
privateproperties with no setters.Returning a new instance with changed values (e.g.,
return new self($newValue)).Benefits: Prevents side effects in large applications, makes Value Objects (like
MoneyorDateTimeImmutable) predictable, and simplifies debugging.
35. What are Generics in PHP?
Answer: PHP does not have native runtime Generics.
How it’s handled: We use PHPDoc annotations (e.g.,
/** @return Collection<User> */) which are then validated by static analysis tools like PHPStan or Psalm.Purpose: To ensure type safety in collections and arrays without the performance overhead of runtime checks.
36. The volatile concept in PHP.
Answer:Since standard PHP is single-threaded, deadlocks usually happen at the Database level (MySQL/PostgreSQL) when two requests lock rows in reverse order.
Prevention: Always update tables/rows in a consistent order, keep transactions short, and use database timeouts.
37. Deadlocks in PHP.
Answer: A Deadlock is a situation in multi-threaded programming where two or more threads are blocked indefinitely, waiting for each other to release the resources they need.
- Conditions for Deadlock:
- Mutual Exclusion: Resources cannot be shared.
- Hold and Wait: Threads hold allocated resources while waiting for others.
- No Preemption: Resources cannot be forcibly taken from a thread.
- Circular Wait: A circular chain of threads, each waiting for a resource held by the next.
- Prevention Strategies:
- Avoid Nested Locks: Acquire locks in a consistent order.
- Timeout for Locks: Use tryLock() with a timeout to avoid indefinite waiting.
- Resource Ordering: Establish a global order for acquiring resources.
- Avoid Starvation: Ensure all threads eventually get access to resources.
- Detection: Thread dumps can reveal deadlock situations. Tools like jstack can analyze thread dumps to identify deadlocked threads.
38. wait(), notify(), and notifyAll() equivalents.
Answer:
These are not in the PHP core.
In Swoole or ReactPHP, you use Event Loops and Promises.
In System-level programming (PCNTL), you use
pcntl_wait()to coordinate between parent and child processes.
39. What is the equivalent of ExecutorService?
Answer: PHP uses Message Queues or Task Workers.
Instead of a thread pool, we use Redis/RabbitMQ with workers (Laravel Queues, Symfony Messenger).
Advantages: Better scalability (workers can be on different servers), fault tolerance (if a worker crashes, the task stays in the queue), and non-blocking user experience.
40. CompletableFuture equivalent: Fibers and Promises.
Answer:* Fibers (PHP 8.1+): Allow for interruptible functions, enabling non-blocking I/O in a way that looks synchronous.
Promises: Used in libraries like Guzzle or ReactPHP to handle asynchronous HTTP calls or database queries without blocking the execution of the rest of the script.
41. Lambda Expressions and Functional Interfaces.
Answer:
Lambdas (Anonymous Functions):
function($a) { return $a; };Arrow Functions (PHP 7.4+):
fn($a) => $a * 2;(These capture the parent scope automatically).Functional Interfaces: PHP doesn’t name them, but any
callableor an object implementing the__invoke()magic method acts as a functional interface.
42. Stream API vs. PHP Array Functions.
Answer: PHP uses Nullable Types (?string $name) and the Null Coalescing Operator (??).
Problem Solved: PHP 8’s Nullsafe Operator (
$user?->getAddress()?->city) solves the “nested null check” problem, preventing “Attempt to read property on null” errors.
43. How does PHP handle the "Optional" concept?
Answer: PHP solves the null-handling problem through Nullable Types, the Null Coalescing Operator, and the Nullsafe Operator. These features force (or allow) developers to handle the absence of a value cleanly without verbose if ($x !== null) checks.
44. Discuss the Singleton Design Pattern in PHP.
Answer:
The Singleton pattern ensures a class has only one instance and provides a global point of access to it.
Pros:
- Useful for database connections or configuration settings.
- Saves resources by not recreating expensive objects.
Cons:
In PHP, a Singleton only lasts for one request. It is destroyed after the script finishes.
Makes unit testing difficult (global state).
Implementation (Thread-safe note): Since standard PHP is single-threaded per request, we don’t need complex “Double-Checked Locking.” A simple static instance works:
class Database {
private static $instance = null;
// 1. Private constructor prevents 'new' from outside
private function __construct() {}
// 2. Prevent cloning
private function __clone() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
45. What is Dependency Injection (DI) in PHP?
Answer: DI is a technique where an object receives its dependencies from the outside rather than creating them internally. In modern PHP, Service Containers (like in Laravel or Symfony) automate this.
46. Explain "Auto-configuration" (Framework level).
Answer: PHP itself doesn’t have “Auto-configuration,” but frameworks like Symfony and Laravel use it.
Laravel Service Provider: Automatically binds interfaces to implementations based on folder structure.
Symfony Autowiring: Reads the type-hints in your constructors and automatically injects the correct service from the container.
47. Purpose of Attributes (PHP 8+) vs Annotations.
Answer: Java uses @Annotations. PHP 8 introduced Attributes (#[Attribute]), which provide metadata for classes and methods without needing to parse docblock comments. This is used by frameworks for routing and ORM (Object-Relational Mapping).
48. Microservices Communication in PHP.
Answer:
Synchronous: Using Guzzle HTTP or cURL for REST/gRPC calls.
Asynchronous: PHP excels here using Queues (Laravel Queue, Symfony Messenger). Instead of internal threads, PHP pushes tasks to Redis or RabbitMQ.
Service Discovery: Often handled via Consul or Kubernetes environment variables.
49. How to resolve performance bottlenecks in PHP?
Answer:
OPcache: Always ensure OPcache is enabled; it stores precompiled script bytecode in shared memory.
Profiling: Use Xdebug or Blackfire.io to see which functions are slow.
Database: 90% of PHP bottlenecks are slow SQL queries. Use
EXPLAINand add indexes.External Calls: Use caching (Redis/Memcached) to avoid hitting slow APIs repeatedly.
50. Garbage Collection (GC) in PHP.
Answer: PHP uses Reference Counting with a Cycle Collector.
Reference Counting: Every variable has a “refcount.” When it hits 0, memory is freed.
Cycle Collection: Specifically cleans up “Circular References” (Object A points to B, and B points to A) that refcounting alone can’t solve.
Note: Unlike Java, you rarely tune PHP GC. Memory is usually freed entirely at the end of the HTTP request.