PHP Interview Question & Answer


What is PHP?

PHP stands for "Hypertext Preprocessor" a widely-used, open-source, server-side scripting language ideal for building dynamic websites, web applications, and mobile APIs.

It supports a wide range of databases, including:MySQL, PostgreSQL, Oracle, Sybase, Solid, Generic ODBC

PHP Originally developed by Rasmus Lerdorf in 1994, PHP has grown into a powerful tool for building interactive and data-driven websites.

What is a session in PHP?

A session is a way to store information (variables) across multiple pages.

Session data is stored on the server and stored on the user's browser.

Session is a temporary storage Data while close the browser then the session times out.

Session unique ID assigns to unique ID (PHPSESSID) of each session.

The Start a session session_start();

Set session variables: $_SESSION['username'] = 'john_doe';

Access session variables echo $_SESSION['username'];

Unset or destroy a session unset($_SESSION['username']); session_destroy();

What are cookies?

A Cookies is store information client computer your web browser.

They store data about a user on the browser.

Session is a temporary storage Data while close the browser then the session times out.

Session Cookies: Temporary; deleted when you close your browser.

Persistent Cookies Stored on your device for a set time.

Setcookie setcookie(name, value, expire, path, domain, secure, httponly);

What is the difference between the include() and require() functions?

Both are used to include a file within another PHP script

include() function If the file is not found or fails to load, include() generates a warning (E_WARNING), but the script continues to execute.

require(): When the file is require cannot be found, it will produce a fatal error (E_COMPILE_ERROR) and stops the execution of the script.

What is the difference between the $_GET[] and $_POST[]?

$_GET[]$_POST[]
Appended to the URL (query string)Sent in the HTTP request body.
Visible in the URL (e.g., ?id=123)Hidden from the URL.
Maximum Length Limited 2000 charactersNo significant limit.
Use Case For retrieving data (search, filters, links)For submitting sensitive or large data (login, form submission).
Not Security visible in browser history and server logsMore secure for confidential data.
Can be cachedNot cached
echo $_GET['name'];echo $_POST['email'];

What is the difference between the echo and print?

EchoPrint
echo can output one or more strings.print can only output one string and it always returns 1.
echo is faster than print because it does not return any value.print is slower compared to echo.
If you want to pass more than one parameter to echo, a parenthesis should be used.Use of parenthesis is not required with the argument list.
Supports multiple arguments: echo "A", "B";Only one argument: print("A");.

What does PEAR stands for?

PEAR stands for “PHP Extension and Application Repository”. PEAR is a framework and repository for all of the reusable PHP components.

A structured library of open-source code for PHP developers.

A command-line tool to install packages.

A standardized way to write and share PHP code.

What is Variables in PHP?

Variablesare "containers" for storing information.

$ sign A variable starts with the $ sign, followed by the name of the variable.

Underscore variable A variable name must start with a letter or the underscore character.

Number variableA variable name cannot start with a number.

Alpha numericA variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

Case sensitiveVariable names are case-sensitive ($age and $AGE are two different variables)

$a = '1';
echo $b = &
$a;
echo $c= "2$b";
First Output: 1;
Second Output: 21;
$i = 5;
echo $i++; // 5
echo $i++; // 6
echo ++$i; // 8
echo $i //8

What is the difference between ASP.NET and PHP?

ASP.NETPHP
A web application framework.A server-side scripting language.
It is designed for use on WindowsIt is Platform independent.
Code is compiled and executed.Interpreted mode of execution.
It has a license cost associated with it.PHP is open-source and freely available.

Explain the main types of errors.

Notices Notices are non-critical errors that can occur during the execution of the script. These are not visible to users.

Warnings: error are more critical than notices. Warnings don’t interrupt the script execution. By default, these are visible to the user. Example: include() a file that doesn’t exist..

Fatal: This is the most critical error type and Happens when PHP cannot continue execution. example: require() a non-existent file

ini_set('display_errors', 1):Purpose of display errors on the browser screen.

ini_set('display_startup_errors', 1): Purpose of PHP to display errors that occur during PHPs startup sequence.

error_reporting(E_ALL):Purpose of which types of errors should be reported, Report all types of errors display.

ini_set('display_errors', 0):Purpose of Disables error display , Do not show errors to users.

ini_set('log_errors', 1):When set to 1, Log errors to a file.

What is the difference between the in_array() and is_array() and array_search functions?

is_array() Checks if a variable is an array.

if (is_array($data))

in_array():Checks if a value exists in an array.

if (in_array('green', $colors))

array_search():Searches an array for a value and returns the key/index if found.

$key = array_search('green', $colors);

What is Composer?

Composer is a dependency management tool for PHP.

It allows you to install, manage, and update external libraries (packages) that your project depends on.

Composer Update: update all dependencies to the newest version allosed by your composer.json

Download and install the latest allowed packages versions

Update the composer.lock file when you want to upgrade package to newer versions

When you want to refresh the package list after modifying composer.json and set the path

Composer install:Install dependencies listed in your composer.lock.

you clone a project pr deploy it to a server

Read composer.lock and install exact versions of package

if no composer.lock exist it all back to composer.json and create a composer.lock

Composer- dump-autoload:regenerate the autoload files.

You are added new classes, removed classes or changed

Namespaced - but didnot change composer.json

No package installation or update Happens, just refresh vendor- autoload.php

How to wesite optimization?

  • Implemeting caching machanisms.

  • Efficient algorithems and data structures.

  • Optimizing database query.

  • Removed unnessary join.

  • Remove Un-nessary function.

  • Minimizing database need of

  • Some data store in localization store local

  • Use a CDN (Content Delivery Network): Like Cloudflare or AWS CloudFront

  • Use browser caching to store static files locally.

  • Compress images: Use tools like TinyPNG or WebP format.

  • Lazy load images and videos to reduce initial load time.

  • Use responsive design (CSS media queries or frameworks like Bootstrap).

  • Use indexing for faster queries and Use pagination or limit results for large data sets.

  • Code Remove unused scripts and styles.

  • Use HTTPS (SSL certificate) , Keep software, plugins, and libraries up-to-date, Sanitize and validate all user input.

  • Website speed optimization: Reducing file sizes, optimizing images, enabling browser caching

  • for Website optimization is check of using gtmetrix,PageSpeed Insights or https://pagespeed.web.dev/

Explain the __construct() and __destruct () method in PHP.

__construct(): If you create a __construct() function, php will automatically call this function when you create an object from a class.

  • class Mobile {
      public $name;
      public $color;
    function __construct($name) {
      $this->name = $name;
    }
    function get_name() {
      return $this->name;
    }
    }
    $iphone = new Mobile("iphone");
    echo $iphone->get_name();

__destruct(): If you create a __destruct() function, PHP will automatically call this function at the end of the script.

  • class Mobile {
      public $name;
      public $color;
    function __construct($name) {
      $this->name = $name;
    }
    function __destruct() {
      echo "The Mobile is {$this->name}.";
    }
    function get_name() {
      return $this->name;
    }
    }
    $iphone = new Mobile("iphone");
    echo $iphone->get_name();

Explain the significance of the header() function in PHP.

The header() function in PHP is used to send raw HTTP headers to the browser before any output is sent..

Syntax: header(string $header, bool $replace = true, int $response_code = 0);.

Redirecting a Page: header("Location: https://example.com"); exit;.

Setting Content-Type: header("Content-Type: application/json");

Force File Download:

  • header("Content-Disposition: attachment; filename=\"file.pdf\"");
  • header("Content-Type: application/pdf");
  • readfile("file.pdf");

Custom Status Codes: header("HTTP/1.1 404 Not Found");

Cache Control:

  • header("Cache-Control: no-cache, must-revalidate");
  • header("Expires: Sat, 1 Jul 2000 05:00:00 GMT");

File access Control:

  • header("Access-Control-Allow-Origin: *"); // allow frontend
  • header("Access-Control-Allow-Methods: POST, GET, OPTIONS"); // Allow methods
  • header("Access-Control-Allow-Headers: Content-Type"); // Allow headers (like Content-Type)
  • header("Access-Control-Allow-Headers: Content-Type, Authorization");
  • header("Access-Control-Allow-Credentials: true");

Explain dependency injection in PHP.

Dependency Injection (DI) is a design pattern used in PHP to pass dependencies (like objects or services) into a class or Constructor, rather than letting the class create them itself.

Simple Definition: Dependency Injection is a technique where an object receives other objects it depends on, instead of creating them internally.

Constructor Injection: Most common; dependencies passed via the constructor.

Setter Injection: Dependencies passed via public setter methods.

Interface Injection:Dependency passed via an interface method.

  • class Database {
    public function connect() {
      return "Connected to DB";
    }
    }
    class UserService {
    private $db;
    // Dependency Injection via constructor public function __construct(Database $db) {
      $this->db = $db;
    }
    public function getUser() {
      return $this->db->connect();
    }
    }
    // Inject dependency from outside
    $db = new Database();
    $userService = new UserService($db);
    echo $userService->getUser()

What's the significance of PSR standards in PHP?

PSR PHP Standard recommendation.

ites a set of coding standards and guidelines for php designed to promote consistency

PSP-1: basic coding standard defines basic rules like using php tags, properClass naming convestions getClassName()

PSR-2:Coding style guid, code formating rules like indentation, line lenght,spacing.

PSR-12: extended coding style guide -code formatting including whitespace, visibility and method declaration.

PSR-4:Autoloading standard - autoloading classes using namespaces , its widly used.

PSR-7:HTTP message interface- http request and responses.

PSR-11:container interface.

PSR-14:Event dispatches.

PSR-15:HTTP server request handles.

What's the OOPs PHP?

Class: Classes define the blueprint for creating objects.

Object: Objects are instance of classes an instance of a class containing real data and behavior.

Encapsulation:Encapsulation involves restricting access to certain class members to prevent direct modification from outside the class with the help of getters and setters.

Access Modifies:

  • Public: Accessible from any where - inside or outside the class.
  • Protected: Accessible within the class and by inheriting class or derived class.
  • Private:Accessible only within the class itself.
  • Getters:Allow you to retrieving the value of private properties.
  • Setters:Allow you to modify the values of private properties sately.
  • class user {   public $name; public function setName($newName) {   return $this->name = $newName; } public function getName() {   return $this->name; } } $user = new user(); echo $user->setName('codekredit'); echo $user->getName(); echo $user->name(); // error connot access private properties

Inheritance: a class can inherit properties and methods from another class.

Polymorphism: a methods can behave differently based on the object calling them .

Overloading and Overriding :

Overloading : Function overloading contains same function name but different argument passing.

PHP overloading not supports

Overloading in PHP refers to dynamically creating properties or methods at runtime using magic methods like:_get() __set(), __call() (for methods) ,__isset() / __unset()

class OverloadExample {
  public function __call($name, $arguments) {
  echo "Method $name called with arguments: " . implode(', ', $arguments);
}
}
$obj = new OverloadExample();
$obj->hello('Aryan'); // Triggers __call()

Overriding : same properies overriding both parent and child classes should have same funciton and argument.

class ParentClass {
  public function greet() {
  echo "Hello from Parent";
}
}
class ChildClass extends ParentClass {
  public function greet() {
  echo "Hello from Child";
}
}
$obj = new ChildClass();
$obj->greet(); // Output: Hello from Child

Abstract Class and Interface class :

AbstractInterface
Abstract class can have both defined method and property.Interface only can have method signature
Abstract class cannot be create object only extendsInterface cannot create object instantiated only Implements.
Abstract Class can have modify access public, protected, private methods.Interface class methods are access public.
Abstract class can have constructor.Cannot have a constructor
Child classes must extend the abstract class and implement its abstract methods.A class that implements an interface must implement all its methods.
Abstract class single inheritance(one class).Interface class multiple inheritance
abstract class Animal {
  abstract public function makeSound();
public function sleep() {
  echo "Sleeping";
}
}
class Dog extends Animal {
  public function makeSound() {
  echo "Woof";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Woof!
$dog->sleep(); // Output: Sleeping...
$test = New Animal(); // wrong not direct object create
interface Shape {
  public function area();
  public function perimeter();
}
class Circle implements Shape {
  private $radius;
  public function __construct($r) {
    $this->radius = $r;
}
public function area() {
  return pi() * $this->radius ** 2;
}
public function perimeter() {
  return 2 * pi() * $this->radius;
}
}
$circle = new Circle(5);
echo $circle->area(); // Output: 78.539...

What is Static Class?

A static class is a class that cannot be instantiated and can’t create objects.

Only contains static methods and variables.

PHP does not have a "static class" keyword, but you can make all methods static:

class MathHelper {
public static function add($a, $b) {
  return $a + $b;
}
}
$result = MathHelper::add(4, 6); // call ::

What is Final Class?

A Final Class cannot be extended any other class.

A Final method cannot be overridden by subclasses.

final class Car {
public function drive() {
  echo "Drivering the car";
}
}
$car = New Car();
$car->drive();

What are SOLID principles?

  • S – Single Responsibility Principle (SRP)

    A class should have one responsibility and only one reason to change.

    Each class should do only one job.

    // ❌ Bad: One class handles both user data and email
    class User {
      public function save() { /* Save user */ }
      public function sendEmail() { /* Send email */ }
    }
    // ✅ Good: Split responsibilities
    class User {
      public function save() { /* Save user */ }
    }
    class EmailService {
      public function sendEmail(User $user) { /* Send email */ }
    }
  • O – Open/Closed Principle (OCP)

    A class should be open for extension, but closed for modification

    You should be able to extend a class's behavior without modifying it..

    // ❌ Bad: Need to change this class every time we add a new payment method
    class Payment {
    public function pay($type) {
    if ($type == 'paypal') { /* PayPal logic */ }
    if ($type == 'card') { /* Card logic */ }
    }
    }
    // ✅ Good: Use inheritance to extend behavior
    interface PaymentMethod {
    public function pay();
    } class PayPal implements PaymentMethod {
    public function pay() { echo "Pay with PayPal"; }
    } class CreditCard implements PaymentMethod {
    public function pay() { echo "Pay with Card"; }
    }
    function makePayment(PaymentMethod $payment) {
    $payment->pay();
    }
  • L – Liskov Substitution Principle (LSP)

    Objects of a subclass should be substitutable for objects of the superclass without altering correctness.

    Subtypes must be substitutable for their base types.

    Any child class should be usable in place of the parent class without breaking the app.

    class Bird {
    public function fly() { echo "Flying"; }
    }
    class Ostrich extends Bird {
    public function fly() { throw new Exception("I can't fly"); } // ❌ Violates LSP
    }
    //Fix by restructuring the hierarchy:
    abstract class Bird { }
    class FlyingBird extends Bird {
    public function fly() { echo "Flying"; } //right
    }
    class Ostrich extends Bird { }
  • I – Interface Segregation Principle (ISP)

    A client should not be forced to implement interfaces it does not use.

    Split large interfaces into smaller, more specific ones.

    // ❌ Bad: Animal interface forces all to implement fly()
    interface Animal {
    public function eat();
    public function fly();
    }
    class Dog implements Animal {
    public function eat() {
    echo "Dog eating";
    }
    public function fly() {
    }
    // ❌ Dog can't fly
    }
    // ✅ Good: Separate interfaces
    interface Animal {
    public function eat();
    }
    interface Flyable {
    public function fly();
    }
    class Dog implements Animal {
    public function eat() { echo "Dog eating";
    }
    }
    class Bird implements Animal, Flyable {
    public function eat() {
    echo "Bird eating";
    }
    public function fly() {
    echo "Bird flying";
    }
    }
  • D – Dependency Inversion Principle (DIP)

    Depend on abstractions, not on concretions.

    High-level modules should not depend on low-level modules. , but both should depend on abstractions Or interfaces.

    // ❌ Bad: Tightly coupled
    class MySQL {
    public function connect() {
    /* MySQL connection */
    }
    }
    class App {
    private $db;
    public function __construct() {
    $this->db = new MySQL(); // tightly coupled
    }
    }
    // ✅ Good: Use an interface
    interface Database {
    public function connect();
    }
    class MySQL implements Database {
    public function connect() {
    /* MySQL connection */
    }
    }
    class MongoDB implements Database {
    public function connect() {
    /* MongoDB connection */
    }
    }
    class App {
    private $db;
    public function __construct(Database $db) {
    $this->db = $db;
    }
    }

What is MVVM?

MVVM stands for Model-View-ViewModel.

Model: The Model represents the data and business logic of the application.

View: The View is the user interface of the application. It is responsible for displaying the data that the Model provides.

Controller: The Controller acts as an intermediary between the Model and the View.

ViewModel: The ViewModel serves as the middle-man between the Model and the View.

What design pattern?

  • 1. Factory Pattern: a method that creates and returns objects without exposing the instantiation logic
    • class Automobile {
      private $bikeMake;
      public function __construct($make, $model) {
      $this->bikeMake = $make;
      }
      public function getMakeAndModel() {
      return $this->bikeMake;
      }
      }
      class AutomobileFactory {
      public static function create($make, $model) {
      return new Automobile($make, $model);
      }
      }
      $pulsar = AutomobileFactory::create('ktm', 'Pulsar');
      print_r($pulsar->getMakeAndModel());
  • 2. Singleton: make sure that a class has one instance of a class that is produced like database connection and mailer class
    • class Singleton {
      private static $instance;
      private function __construct() {
      }
      private function __clone() {
      }
      }
      public static function getInstance() {
      if (self::$instance === null) {
      self::$instance = new Singleton();
      }
      return self::$instance;
      }
      $singleton = Singleton::getInstance();
  • 3. Repository Pattern: It is a collection of domain objects, acting like an in-memory collection. The repository is responsible for providing access to data.
  • 4. Observer Pattern: Allows a subject to notify a list of observers when its state changes.
    • class Subject {
      private $observers = [];
      public function addObserver(Observer $observer) {
      $this->observers[] = $observer;
      }
      public function notifyObservers($state) {
      foreach ($this->observers as $observer) {
      $observer->update($state);
      }
      }
      }
      $subject = new Subject();
      $observer1 = new ConcreteObserver();
      $observer2 = new ConcreteObserver();
      $subject->addObserver($observer1);
      $subject->addObserver($observer2);
      $subject->notifyObservers("New state");