Give MCQs test (placement preparation)

🔹 Basic Level Answers

1. What is MySQL?

MySQL is a relational database management system (RDBMS) that stores data in tables.

👉 SQL = language
👉 MySQL = software that uses SQL


2. What is PDO? Why use it?

PDO (PHP Data Objects) is a database abstraction layer.

✅ Supports multiple DBs
✅ Secure (prepared statements)
✅ OOP based


3. MySQLi vs PDO

  • MySQLi → Only MySQL
  • PDO → Multiple DBs (MySQL, PostgreSQL, etc.)

👉 Interview line: “PDO is more flexible and reusable.”


4. Primary Key

Unique identifier for each row.

id INT AUTO_INCREMENT PRIMARY KEY

5. CRUD

  • Create → INSERT
  • Read → SELECT
  • Update → UPDATE
  • Delete → DELETE

6. PDO Connection

$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

7. fetch() vs fetchAll()

  • fetch() → single row
  • fetchAll() → multiple rows
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

🔹 Intermediate Answers

1. Prepared Statements 🔥

Precompiled SQL queries that prevent SQL injection.

$stmt = $conn->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);

2. SQL Injection

Malicious SQL input.

❌ Unsafe:

$sql = "SELECT * FROM users WHERE email = '$email'";

✅ Safe:

$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);

3. bindParam vs bindValue

  • bindParam() → binds variable (by reference)
  • bindValue() → binds actual value

4. rowCount()

Returns affected rows.

$stmt->rowCount();

5. Error Handling

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

6. lastInsertId()

$conn->lastInsertId();

7. Index

Improves query speed.

CREATE INDEX idx_email ON users(email);

8. INNER JOIN vs LEFT JOIN

  • INNER → matching rows only
  • LEFT → all left + matched right

🔹 Advanced Answers

1. How PDO prevents SQL Injection

  • Separates SQL & data
  • Escapes input automatically

2. Transactions 🔥

Used for multiple queries safely.

$conn->beginTransaction();try {
$conn->exec("INSERT INTO users (name) VALUES ('A')");
$conn->exec("INSERT INTO orders (user_id) VALUES (1)");
$conn->commit();
} catch(Exception $e) {
$conn->rollback();
}

3. commit vs rollback

  • commit() → save changes
  • rollback() → undo changes

4. Optimize queries

  • Use indexes
  • Use LIMIT
  • Avoid SELECT *
  • Use proper joins

5. CHAR vs VARCHAR

  • CHAR → fixed length
  • VARCHAR → dynamic

6. Password Security 🔥

$password = password_hash($pass, PASSWORD_DEFAULT);
password_verify($pass, $hash);

7. ACID Properties

  • Atomicity
  • Consistency
  • Isolation
  • Durability

🔹 Practical Coding Answers

1. Insert User

$stmt = $conn->prepare("INSERT INTO users(name,email) VALUES (?,?)");
$stmt->execute([$name,$email]);

2. Login System

$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();if($user && password_verify($pass,$user['password'])){
echo "Login success";
}

3. Fetch Users

$stmt = $conn->query("SELECT * FROM users");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

4. Update

$stmt = $conn->prepare("UPDATE users SET email=? WHERE id=?");
$stmt->execute([$email,$id]);

5. Delete

$stmt = $conn->prepare("DELETE FROM users WHERE id=?");
$stmt->execute([$id]);

6. Search

$stmt = $conn->prepare("SELECT * FROM users WHERE name LIKE ?");
$stmt->execute(["%$name%"]);

7. Pagination

$limit = 10;
$offset = 0;$stmt = $conn->prepare("SELECT * FROM users LIMIT ? OFFSET ?");
$stmt->bindValue(1, $limit, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();

8. JOIN Query

$stmt = $conn->query("
SELECT users.name, orders.id
FROM users
INNER JOIN orders ON users.id = orders.user_id
");

🔹 Scenario Answers (Impress Interviewer)

1. DB hacked?

  • Change credentials
  • Backup restore
  • Patch vulnerability
  • Use prepared statements

2. Handle 1M records?

  • Indexing
  • Pagination
  • Caching
  • Optimized queries

3. Secure login system?

  • password_hash()
  • Prepared statements
  • Sessions
  • CSRF protection

🔥 Final Interview Line

Say this confidently:

“I always use PDO with prepared statements, password hashing, transactions where needed, and proper indexing to ensure both security and performance.”

real interview questions (PHP + MySQL PDO)

🔹 Basic Level Questions

  1. What is MySQL? Difference between SQL and MySQL?
  2. What is PDO in PHP? Why use it?
  3. Difference between MySQLi and PDO?
  4. What is a database table?
  5. What is a primary key?
  6. What is AUTO_INCREMENT?
  7. What is CRUD? Explain each operation.
  8. How do you connect PHP with MySQL using PDO?
  9. What is fetch() vs fetchAll()?
  10. What is PDO::FETCH_ASSOC?

🔹 Intermediate Level Questions

  1. What are prepared statements? Why are they important? 🔥
  2. What is SQL Injection? How do you prevent it?
  3. Difference between:
    • bindParam() vs bindValue()
  4. What is rowCount()?
  5. How to handle errors in PDO?
  6. What is lastInsertId()?
  7. What is the difference between:
    • require vs include (used in DB connection files)
  8. What is normalization in database?
  9. What are indexes in MySQL?
  10. What is the difference between INNER JOIN and LEFT JOIN?

🔹 Advanced Level Questions

  1. How does PDO protect against SQL Injection internally?
  2. What are transactions in PDO? Explain with example.
  3. Difference between:
    • commit()
    • rollback()
  4. How to optimize slow queries in MySQL?
  5. What is connection pooling?
  6. What is the difference between:
    • CHAR vs VARCHAR
  7. What is database locking?
  8. How do you secure user authentication system in PHP?
  9. What is hashing? Difference between:
    • md5()
    • password_hash() 🔥
  10. What are ACID properties in databases?

🔹 Practical Coding Questions (Very Important 🔥)

  1. Write a PDO query to insert user data securely
  2. Create a login system using prepared statements
  3. Fetch all users and display in table
  4. Update user email using PDO
  5. Delete a user by ID
  6. Create a search feature (LIKE query)
  7. Implement pagination in PHP + MySQL
  8. Build a secure registration system with hashed passwords
  9. Write a JOIN query using PDO
  10. Create a REST API using PHP + PDO

🔥 HR + Scenario-Based Questions

  1. What will you do if your database is hacked?
  2. How will you handle 1 million records efficiently?
  3. How do you design a scalable database?
  4. How do you debug a slow query?
  5. What steps will you take to secure a login system?

💡 Pro Tip (Interview Hack)

If you say this line, interviewer gets impressed:

“I always use PDO prepared statements with password_hash() and proper validation to prevent SQL injection and ensure security.”


Build a mini project (login system using PDO)

I’ve built a complete PDO Login System Mini Project for you in the canvas 👉

What this project includes:

  • ✅ Database connection (PDO)
  • ✅ User registration (with password hashing 🔐)
  • ✅ Secure login (with password_verify)
  • ✅ Session-based authentication
  • ✅ Dashboard page
  • ✅ Logout system

How to run:

  1. Create database: test_db
  2. Run the table SQL (already included in code)
  3. Save files:
    • db.php
    • register.php
    • login.php
    • dashboard.php
    • logout.php
  4. Open register.php → create account
  5. Then go to login.php
<?php
// ===============================
// DATABASE CONNECTION (db.php)
// ===============================
$host = 'localhost';
$db   = 'test_db';
$user = 'root';
$pass = '';

try {
    $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}


// ===============================
// CREATE TABLE (Run in MySQL)
// ===============================
/*
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100) UNIQUE,
    password VARCHAR(255)
);
*/


// ===============================
// REGISTER (register.php)
// ===============================
if(isset($_POST['register'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :password)");
    $stmt->execute([
        ':name' => $name,
        ':email' => $email,
        ':password' => $password
    ]);

    echo "Registered Successfully";
}
?>

<form method="POST">
    <h2>Register</h2>
    <input type="text" name="name" placeholder="Name" required><br>
    <input type="email" name="email" placeholder="Email" required><br>
    <input type="password" name="password" placeholder="Password" required><br>
    <button type="submit" name="register">Register</button>
</form>


<?php
// ===============================
// LOGIN (login.php)
// ===============================
session_start();

if(isset($_POST['login'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email");
    $stmt->execute([':email' => $email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if($user && password_verify($password, $user['password'])) {
        $_SESSION['user'] = $user['name'];
        header("Location: dashboard.php");
    } else {
        echo "Invalid Credentials";
    }
}
?>

<form method="POST">
    <h2>Login</h2>
    <input type="email" name="email" placeholder="Email" required><br>
    <input type="password" name="password" placeholder="Password" required><br>
    <button type="submit" name="login">Login</button>
</form>


<?php
// ===============================
// DASHBOARD (dashboard.php)
// ===============================
session_start();

if(!isset($_SESSION['user'])) {
    header("Location: login.php");
}

echo "Welcome " . $_SESSION['user'];
?>

<a href="logout.php">Logout</a>


<?php
// ===============================
// LOGOUT (logout.php)
// ===============================
session_start();
session_destroy();
header("Location: login.php");
?>

12. Database (MySQL) (PHP)

1️⃣ Introduction to MySQL

  • MySQL is a relational database management system (RDBMS).
  • It stores data in tables (rows & columns).
  • Uses SQL (Structured Query Language).

Key Concepts:

  • Database → Collection of tables
  • Table → Collection of records
  • Row → Single record
  • Column → Field (name, email, etc.)

Example:

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);

2️⃣ Connecting PHP with MySQL

PHP connects to MySQL using:

  • MySQLi (procedural & OOP)
  • PDO (recommended for flexibility)

MySQLi Example:

$conn = mysqli_connect("localhost", "root", "", "test_db");if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

PDO Example:

try {
$conn = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

3️⃣ MySQLi vs PDO

FeatureMySQLiPDO
Database SupportOnly MySQLMultiple DBs
API StyleProcedural + OOPOOP only
SecurityGoodBetter (more flexible)
Prepared StatementsYesYes

👉 Best Practice: Use PDO in modern applications.


4️⃣ CRUD Operations

CRUD = Create, Read, Update, Delete

🔹 Create (Insert)

$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";
$conn->exec($sql);

🔹 Read (Select)

$stmt = $conn->query("SELECT * FROM users");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);foreach ($data as $row) {
echo $row['name'];
}

🔹 Update

$sql = "UPDATE users SET name='Jane' WHERE id=1";
$conn->exec($sql);

🔹 Delete

$sql = "DELETE FROM users WHERE id=1";
$conn->exec($sql);

5️⃣ Prepared Statements (Very Important 🔥)

👉 Prevents SQL Injection (security attacks)

❌ Unsafe Query:

$name = $_GET['name'];
$sql = "SELECT * FROM users WHERE name = '$name'";

✅ Safe Prepared Statement (PDO):

$stmt = $conn->prepare("SELECT * FROM users WHERE name = :name");
$stmt->bindParam(':name', $name);
$stmt->execute();$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

MySQLi Prepared:

$stmt = $conn->prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $name);
$stmt->execute();

🔥 Pro Tips (Important for Students)

  • Always use prepared statements
  • Never trust user input ($_GET, $_POST)
  • Use try-catch in PDO
  • Use LIMIT in queries for performance
  • Close connections properly

HR Interview Questions (with strong answers)

1. Tell me about yourself

👉 Keep it structured: Present + Skills + Goal

Answer:
“I am Aditya Kumar Singh, working on web development with a strong focus on PHP and OOP. I run SOA Technology where I build real-world projects like AI tools and web applications. I enjoy solving problems and building scalable systems. Currently, I am improving my backend architecture skills and aiming to work on larger production-level applications.”


2. Why should we hire you?

Answer:
“I have practical experience building real projects, not just theory. I understand OOP, MVC, and backend logic, and I focus on writing clean and maintainable code. I can quickly adapt and contribute to real-world projects.”


3. What are your strengths?

Answer:

  • Problem-solving
  • Fast learning
  • Real project experience

4. What are your weaknesses?

Answer (safe & smart):
“Sometimes I spend extra time optimizing code, but I’m learning to balance optimization with deadlines.”


5. Why do you want this job?

Answer:
“I want to work in a professional environment where I can apply my PHP and OOP knowledge to real systems and grow by working with experienced developers.”


6. Where do you see yourself in 5 years?

Answer:
“I see myself as a senior developer or backend architect, working on scalable systems and possibly leading a team.”


7. Describe a challenge you faced

Answer:
“While building a project, I faced issues with routing and structure. I solved it by learning MVC architecture and restructuring my code, which improved performance and maintainability.”


💻 Technical Interview Questions (PHP + OOP)


🟢 Basic

1. Difference between echo and print

  • echo → faster, no return
  • print → returns 1

2. GET vs POST

GETPOST
Visible in URLHidden
Less secureMore secure
Limited dataLarge data

3. What is session?

Used to store user data across pages.


🟡 OOP Focus

4. What is OOP?

Programming using objects and classes to improve structure and reuse.


5. Explain encapsulation with example

class User {
private $password; public function setPassword($p) {
$this->password = password_hash($p, PASSWORD_DEFAULT);
}
}

6. What is inheritance?

Reuse code from parent class.


7. What is polymorphism?

Same method behaves differently.


8. Interface vs Abstract (very common)

Already asked in almost every interview.


🔵 Advanced

9. How do you connect PHP with database?

Using PDO or MySQLi


10. What is PDO?

  • Secure
  • Prevents SQL injection
  • Supports multiple DB

11. How to prevent SQL injection?

  • Prepared statements (PDO)

12. What is MVC?

  • Model → database
  • View → UI
  • Controller → logic

13. What is REST API?

Communication between frontend & backend using JSON.


14. What is dependency injection?

Passing objects instead of creating inside class.


🔴 Real Coding Questions

15. Reverse a string

echo strrev("hello");

16. Check palindrome

$str = "madam";
if ($str == strrev($str)) echo "Palindrome";

17. Find largest number in array

echo max([1,5,9,2]);

18. Simple login logic

if ($user == $dbUser && password_verify($pass, $hash)) {
echo "Login success";
}

🚀 Final Interview Tips (Very Important)

✔ Speak confidently
✔ Give real examples (your projects)
✔ Mention:

  • MVC
  • Security (hashing, PDO)
  • Clean code

✔ Don’t say “I don’t know” → say:
👉 “I haven’t used it much, but I understand the concept…”

important Object-Oriented PHP (OOP) interview questions with answers

🟢 Basic OOP Interview Questions

1. What is OOP in PHP?

OOP (Object-Oriented Programming) is a programming paradigm based on classes and objects. It helps organize code using:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

2. What is a Class and Object?

  • Class → Blueprint of an object
  • Object → Instance of a class
class Car {
public $brand = "BMW";
}$car = new Car(); // object

3. What is a Constructor?

A constructor is a special method called automatically when an object is created.

class Test {
public function __construct() {
echo "Object Created";
}
}

4. What is a Destructor?

It is called when an object is destroyed.

public function __destruct() {
echo "Object Destroyed";
}

🟡 Intermediate Questions

5. What is Encapsulation?

Wrapping data and methods into a single unit and restricting access using:

  • private
  • protected
  • public

6. What is Inheritance?

Acquiring properties and methods of another class.

class ParentClass {}
class ChildClass extends ParentClass {}

7. What is Polymorphism?

Same method, different behavior.

class A { function test(){ echo "A"; } }
class B extends A { function test(){ echo "B"; } }

8. What is Abstraction?

Hiding internal details and showing only functionality using:

  • Abstract classes
  • Interfaces

9. Difference between Abstract Class and Interface?

FeatureAbstract ClassInterface
MethodsBoth abstract & normalOnly abstract
PropertiesAllowedNot allowed
Multiple InheritanceNoYes

10. What are Access Modifiers?

ModifierAccess
publicEverywhere
privateSame class
protectedClass + child

🔵 Advanced Questions

11. What is Late Static Binding?

Allows static methods to be resolved based on the called class, not the declaring class.

class A {
public static function test() {
static::who();
}
public static function who() {
echo "A";
}
}class B extends A {
public static function who() {
echo "B";
}
}B::test(); // Output: B

12. What are Magic Methods?

Special methods starting with __

Examples:

  • __construct()
  • __destruct()
  • __get()
  • __set()
  • __toString()

13. What is Dependency Injection?

Passing dependencies to a class instead of creating inside.

class DB {}
class User {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
}

14. What is Trait in PHP?

Used to reuse code in multiple classes.

trait Logger {
public function log() {
echo "Logging...";
}
}

15. What is Namespace?

Used to avoid class name conflicts.

namespace App\Models;
class User {}

🔴 Scenario-Based Questions (Very Important 🚀)

16. How would you design a login system using OOP?

  • User class
  • Auth controller
  • Database class
  • Password hashing

17. How do you handle database in OOP PHP?

  • Use PDO
  • Create DB class
  • Use Singleton or Dependency Injection

18. What is MVC?

  • Model → Data
  • View → UI
  • Controller → Logic

🎯 Pro Interview Tips

  • Always explain with real examples
  • Mention security (password_hash, PDO)
  • Talk about scalability & clean code
  • Avoid procedural style in answers

Full Php Mvc Oop Project (complete Structure)

I’ve created a complete working MVC OOP PHP project for you in the canvas 👉

This is a basic but real structure you can run and extend.


🚀 How to Run

  1. Create folder structure:
project/
app/
controllers/
models/
views/
core/
public/
  1. Move code into proper files (I kept it in one file for simplicity — you should split it)
  2. Run using:
  • XAMPP / WAMP → localhost/project/public
  • Or PHP built-in server:
php -S localhost:8000

⚠️ Important Improvements (Next Step)

Right now it’s basic, but for real production you should:

🔐 Add Database (MySQL)

  • Use PDO
  • Store users in DB (not array)

🧠 Add Features

  • Sessions (login system)
  • Middleware (auth check)
  • Validation
  • Error handling

📦 Use Autoloading

spl_autoload_register(function($class){
require_once \"../app/$class.php\";
});
<?php
// =============================
// SIMPLE MVC OOP PHP PROJECT
// =============================

// --------- FOLDER STRUCTURE ---------
// /project
//   /app
//     /controllers
//     /models
//     /views
//   /core
//   /config
//   public/index.php

// =============================
// CORE: Router
// =============================
class Router {
    public function route() {
        $url = $_GET['url'] ?? 'home/index';
        $url = explode('/', $url);

        $controllerName = ucfirst($url[0]) . 'Controller';
        $method = $url[1] ?? 'index';

        require_once "app/controllers/$controllerName.php";
        $controller = new $controllerName();

        call_user_func([$controller, $method]);
    }
}

// =============================
// CORE: Controller
// =============================
class Controller {
    public function model($model) {
        require_once "app/models/$model.php";
        return new $model();
    }

    public function view($view, $data = []) {
        require_once "app/views/$view.php";
    }
}

// =============================
// MODEL: User
// =============================
class User {
    private $users = [];

    public function register($name, $password) {
        $this->users[$name] = password_hash($password, PASSWORD_DEFAULT);
    }

    public function login($name, $password) {
        if (isset($this->users[$name]) && password_verify($password, $this->users[$name])) {
            return true;
        }
        return false;
    }
}

// =============================
// CONTROLLER: Home
// =============================
class HomeController extends Controller {
    public function index() {
        $this->view('home');
    }
}

// =============================
// CONTROLLER: Auth
// =============================
class AuthController extends Controller {
    private $user;

    public function __construct() {
        $this->user = new User();
    }

    public function register() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->user->register($_POST['name'], $_POST['password']);
            echo "Registered Successfully";
        }
        $this->view('register');
    }

    public function login() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if ($this->user->login($_POST['name'], $_POST['password'])) {
                echo "Login Success";
            } else {
                echo "Login Failed";
            }
        }
        $this->view('login');
    }
}

// =============================
// VIEW: home.php
// =============================
?>
<h1>Welcome to MVC App</h1>
<a href="?url=auth/register">Register</a>
<a href="?url=auth/login">Login</a>

<?php
// =============================
// VIEW: register.php
// =============================
?>
<form method="POST">
    <input type="text" name="name" placeholder="Name">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Register</button>
</form>

<?php
// =============================
// VIEW: login.php
// =============================
?>
<form method="POST">
    <input type="text" name="name" placeholder="Name">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Login</button>
</form>

<?php
// =============================
// PUBLIC: index.php (ENTRY POINT)
// =============================
require_once '../core/Router.php';
require_once '../core/Controller.php';

$router = new Router();
$router->route();

solutions with PHP OOP code

🟢 Beginner Level

1. Class & Object

class Car {
public $brand;
public $model; public function showDetails() {
echo "Brand: $this->brand, Model: $this->model";
}
}$car1 = new Car();
$car1->brand = "Toyota";
$car1->model = "Fortuner";
$car1->showDetails();

2. Constructor

class Student {
public $name;
public $age; public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
} public function show() {
echo "$this->name is $this->age years old";
}
}$s = new Student("Aditya", 22);
$s->show();

3. Calculator

class Calculator {
public function add($a, $b) {
return $a + $b;
}
public function subtract($a, $b) {
return $a - $b;
}
public function multiply($a, $b) {
return $a * $b;
}
public function divide($a, $b) {
return $b != 0 ? $a / $b : "Cannot divide by zero";
}
}$c = new Calculator();
echo $c->add(5, 3);

🟡 Intermediate Level

4. Inheritance

class Animal {
public function makeSound() {
echo "Animal sound";
}
}class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}class Cat extends Animal {
public function makeSound() {
echo "Meow";
}
}$d = new Dog();
$d->makeSound();

5. Encapsulation

class BankAccount {
private $balance = 0; public function deposit($amount) {
$this->balance += $amount;
} public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
} else {
echo "Insufficient balance";
}
} public function getBalance() {
return $this->balance;
}
}$acc = new BankAccount();
$acc->deposit(1000);
$acc->withdraw(300);
echo $acc->getBalance();

6. Static

class Counter {
public static $count = 0; public static function increment() {
self::$count++;
}
}Counter::increment();
Counter::increment();
echo Counter::$count;

7. Constants

class MathConstants {
const PI = 3.14; public function circleArea($r) {
return self::PI * $r * $r;
}
}$m = new MathConstants();
echo $m->circleArea(5);

🔵 Advanced Level

8. Abstract Class

abstract class Shape {
abstract public function area();
}class Circle extends Shape {
private $r; public function __construct($r) {
$this->r = $r;
} public function area() {
return 3.14 * $this->r * $this->r;
}
}class Rectangle extends Shape {
private $w, $h; public function __construct($w, $h) {
$this->w = $w;
$this->h = $h;
} public function area() {
return $this->w * $this->h;
}
}

9. Interface

interface Payment {
public function pay($amount);
}class CreditCard implements Payment {
public function pay($amount) {
echo "Paid $amount using Credit Card";
}
}class PayPal implements Payment {
public function pay($amount) {
echo "Paid $amount using PayPal";
}
}

10. Polymorphism

class Circle {
public function draw() {
echo "Drawing Circle";
}
}class Square {
public function draw() {
echo "Drawing Square";
}
}function render($shape) {
$shape->draw();
}render(new Circle());
render(new Square());

11. Magic Methods

class User {
public $name; public function __construct($name) {
$this->name = $name;
echo "User Created<br>";
} public function __destruct() {
echo "User Destroyed";
} public function __toString() {
return "User: " . $this->name;
}
}$u = new User("Aditya");
echo $u;

12. File Handling

class FileManager {
public function write($file, $data) {
file_put_contents($file, $data);
} public function read($file) {
return file_get_contents($file);
}
}$f = new FileManager();
$f->write("test.txt", "Hello World");
echo $f->read("test.txt");

🔴 Real-World

13. Simple Login System (Basic)

class User {
private $username;
private $password; public function register($u, $p) {
$this->username = $u;
$this->password = password_hash($p, PASSWORD_DEFAULT);
} public function login($u, $p) {
if ($this->username === $u && password_verify($p, $this->password)) {
return "Login Success";
}
return "Login Failed";
}
}$user = new User();
$user->register("admin", "1234");
echo $user->login("admin", "1234");

14. Shopping Cart

class Product {
public $name, $price; public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
}class Cart {
private $items = []; public function add(Product $p) {
$this->items[] = $p;
} public function total() {
$sum = 0;
foreach ($this->items as $item) {
$sum += $item->price;
}
return $sum;
}
}$cart = new Cart();
$cart->add(new Product("Phone", 10000));
$cart->add(new Product("Laptop", 50000));
echo $cart->total();

15. Blog System (Basic Structure)

class Post {
public $title; public function __construct($title) {
$this->title = $title;
}
}class Comment {
public $text; public function __construct($text) {
$this->text = $text;
}
}class User {
public $name; public function __construct($name) {
$this->name = $name;
}
}

practical Object-Oriented PHP (OOP) practice questions

🟢 Beginner Level

1. Class & Object

Create a class Car with properties:

  • brand
  • model

Create a method showDetails() to print car details.


2. Constructor

Create a class Student with:

  • name
  • age

Initialize values using a constructor and display them.


3. Method Calling

Create a class Calculator with methods:

  • add()
  • subtract()
  • multiply()
  • divide()

🟡 Intermediate Level

4. Inheritance

Create a parent class Animal with method makeSound()
Create child classes:

  • Dog → “Bark”
  • Cat → “Meow”

5. Encapsulation

Create a class BankAccount:

  • private property: balance
  • methods: deposit(), withdraw(), getBalance()

6. Static Methods & Properties

Create a class Counter:

  • static property $count
  • static method increment()

7. Constants

Create a class MathConstants:

  • define PI
  • use it in a method to calculate area of a circle

🔵 Advanced Level

8. Abstract Class

Create abstract class Shape:

  • abstract method area()

Child classes:

  • Circle
  • Rectangle

9. Interface

Create interface Payment:

  • method pay()

Classes:

  • CreditCard
  • PayPal

10. Polymorphism

Create multiple classes with same method draw():

  • Circle
  • Square
  • Triangle

11. Magic Methods

Create a class User:

  • use __construct()
  • use __destruct()
  • use __toString()

12. File Handling with OOP

Create a class FileManager:

  • read file
  • write file

🔴 Real-World Practice (Important 🚀)

13. Mini Project – User Login System

  • Class User
  • Register user
  • Login user
  • Validate password

14. Shopping Cart System

  • Product class
  • Cart class
  • Add/remove items
  • Calculate total

15. Blog System (OOP)

  • Post class
  • Comment class
  • User class

💡 Bonus Interview Questions

  • What is OOP?
  • Difference between Interface & Abstract Class?
  • What is encapsulation?
  • What is polymorphism?
  • What is late static binding?

Give real-world project using OOP (like Login System / API)

I’ve created a complete real-world PHP OOP Login System API project in the canvas 👉

What this project includes:

  • ✅ OOP structure (Database + User class)
  • ✅ Secure password hashing (password_hash)
  • ✅ Login with password_verify
  • ✅ REST API (register & login)
  • ✅ JSON responses (ready for frontend / mobile app)
  • ✅ PDO (secure DB handling)

🚀 How to use this project:

1. Create Database

  • Create DB: test_db
  • Run the SQL (already included at bottom of code)

2. Run API

Put file in:

htdocs/login-api/index.php

3. Test API (Postman / JS)

🔹 Register API

POST http://localhost/login-api/index.php?action=register

Body (JSON):

{
"name": "Aditya",
"email": "test@gmail.com",
"password": "123456"
}

🔹 Login API

POST http://localhost/login-api/index.php?action=login

Body:

{
"email": "test@gmail.com",
"password": "123456"
}
<?php
// ===============================
// DATABASE CONNECTION (PDO)
// ===============================
class Database {
    private $host = "localhost";
    private $db_name = "test_db";
    private $username = "root";
    private $password = "";
    public $conn;

    public function connect() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host={$this->host};dbname={$this->db_name}",
                $this->username,
                $this->password
            );
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo "Connection Error: " . $e->getMessage();
        }
        return $this->conn;
    }
}

// ===============================
// USER CLASS (OOP)
// ===============================
class User {
    private $conn;
    private $table = "users";

    public $id;
    public $name;
    public $email;
    public $password;

    public function __construct($db) {
        $this->conn = $db;
    }

    // REGISTER USER
    public function register() {
        $query = "INSERT INTO {$this->table} (name, email, password) VALUES (:name, :email, :password)";
        $stmt = $this->conn->prepare($query);

        $this->password = password_hash($this->password, PASSWORD_DEFAULT);

        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':email', $this->email);
        $stmt->bindParam(':password', $this->password);

        return $stmt->execute();
    }

    // LOGIN USER
    public function login() {
        $query = "SELECT * FROM {$this->table} WHERE email = :email LIMIT 1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':email', $this->email);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if($row && password_verify($this->password, $row['password'])) {
            return $row;
        }
        return false;
    }
}

// ===============================
// API HANDLER
// ===============================
header("Content-Type: application/json");

$db = (new Database())->connect();
$user = new User($db);

$action = $_GET['action'] ?? '';

if($action === 'register') {
    $data = json_decode(file_get_contents("php://input"));

    $user->name = $data->name;
    $user->email = $data->email;
    $user->password = $data->password;

    if($user->register()) {
        echo json_encode(["status" => "success", "message" => "User registered"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Registration failed"]);
    }
}

if($action === 'login') {
    $data = json_decode(file_get_contents("php://input"));

    $user->email = $data->email;
    $user->password = $data->password;

    $result = $user->login();

    if($result) {
        echo json_encode(["status" => "success", "user" => $result]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid credentials"]);
    }
}

// ===============================
// SQL TABLE
// ===============================
/*
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100) UNIQUE,
    password VARCHAR(255)
);
*/

?>