PHP Basics · Chapter 16 · OOP Fundamentals

PHP OOP — Object Oriented
Programming in Hindi

PHP OOP की पूरी जानकारी — Class, Object, Constructor, Destructor, Properties, Methods, Access Modifiers, Inheritance, static, abstract। Real World examples के साथ।

🏗️ Class & Object ⚙️ Constructor 🔒 Access Modifiers 👪 Inheritance 🔷 Abstract & Static
classBlueprint — Object का template
newObject बनाना
extendsInheritance keyword
$thisCurrent object reference

📋 इस Article में क्या-क्या है

  1. OOP क्या है? — Why?
  2. Class और Object
  3. Properties और Methods
  4. Constructor और Destructor
  5. Access Modifiers
  6. $this keyword
  7. Getter और Setter
  8. Inheritance — extends
  9. Method Overriding
  10. Static Properties & Methods
1
OOP क्या है? — Procedural vs OOP

Object Oriented Programming (OOP) — Code को real-world objects की तरह organize करना। Student, Product, Order — हर चीज़ एक Object है जिसकी properties और behaviors होती हैं।

❌ Procedural Style — Functions scattered

// Data और functions अलग-अलग
$studentNaam = "Rahul";
$studentMarks = 95;
function getGrade($marks) { ... }
function printReport($naam, $marks) { ... }

✅ OOP Style — Data + Methods एक साथ

// Student object में सब कुछ
$student = new Student("Rahul", 95);
echo $student->getGrade();
$student->printReport();
OOP ConceptReal WorldPHP
ClassCar का blueprint/designclass Car { }
ObjectActual car (मेरी Maruti)$myCar = new Car()
PropertyCar का color, speed$this->color = "red"
MethodCar का start(), stop()public function start()
ConstructorCar factory में assemble__construct()
InheritanceElectricCar is a Carclass ElectricCar extends Car

2
Class और Object — Blueprint और Instance
cls
obj

class keyword

Class — Blueprint या template। Object — class का instance (actual copy)। एक class से कई objects बना सकते हो — हर object का अपना data।

class = Template object = Instance new keyword
class ClassName {
  // Properties (variables)
  public string $naam;

  // Methods (functions)
  public function greet(): string {
    return "Hello!";
  }
}

// Object बनाना
$obj = new ClassName();
CLASS और OBJECT — BASIC EXAMPLE
<?php
class Student {
  // Properties
  public string $naam;
  public int $marks;
  public string $school = "HNP School"; // Default value

  // Method
  public function introduce(): string {
    return "मैं {$this->naam} हूँ, {$this->school} से।";
  }
}

// Objects बनाना (Instantiation)
$s1 = new Student();
$s1->naam = "Rahul";
$s1->marks = 95;
echo $s1->introduce(); // मैं Rahul हूँ, HNP School से।

$s2 = new Student();
$s2->naam = "Priya";
$s2->marks = 88;
echo $s2->introduce(); // मैं Priya हूँ, HNP School से।

// दोनों objects अलग — अपना-अपना data
echo $s1->naam; // Rahul
echo $s2->naam; // Priya
?>

3
Constructor और Destructor — __construct / __destruct
__con
struct

__construct()

Object बनते समय automatically call होता है। Properties initialize करना, DB connection खोलना। PHP 8 में Constructor Promotion — parameters directly properties बन जाती हैं।

Auto called PHP 8 Promotion Initialize करने के लिए
CONSTRUCTOR — TRADITIONAL VS PHP 8 PROMOTION
<?php
// Traditional way — verbose
class ProductOld {
  public string $name;
  public float $price;
  public int $stock;

  public function __construct(string $name, float $price, int $stock) {
    $this->name = $name;
    $this->price = $price;
    $this->stock = $stock;
  }
}

// PHP 8 Constructor Promotion — clean!
class Product {
  public function __construct(
    public readonly string $name, // Auto property!
    public float $price = 0.0, // Default value
    public int $stock = 0,
  ) {}
}

$p = new Product("PHP Book", 450.00, 10);
echo $p->name; // PHP Book
echo $p->price; // 450

// Constructor में logic भी
class BankAccount {
  private float $balance;
  private array $transactions = [];

  public function __construct(float $initialBalance = 0.0) {
    if ($initialBalance < 0) {
      throw new InvalidArgumentException("Balance negative नहीं हो सकता");
    }
    $this->balance = $initialBalance;
  }

  // Destructor — object destroy होने पर
  public function __destruct() {
    echo "Account closed. Final balance: ₹{$this->balance}";
  }
}
?>

4
Access Modifiers — public, protected, private
🔒
mod

Access Modifiers

Properties और Methods की visibility control करते हैं — कहाँ से access हो सकता है। Encapsulation — OOP का core principle।

public — सब access protected — class+children private — सिर्फ class
ModifierSame ClassChild ClassOutsideUse Case
publicAPI, getters, public methods
protectedInheritance में reuse
privateInternal state, sensitive data
ACCESS MODIFIERS — EXAMPLE
<?php
class User {
  public string $naam; // सब access कर सकते हैं
  protected string $email; // Class + children
  private string $password; // सिर्फ इस class में

  public function __construct(string $naam, string $email, string $pass) {
    $this->naam = $naam;
    $this->email = $email;
    $this->password = password_hash($pass, PASSWORD_BCRYPT);
  }

  public function verifyPassword(string $pass): bool {
    return password_verify($pass, $this->password); // OK — same class
  }
}

$user = new User("Rahul", "r@g.com", "pass123");
echo $user->naam; // ✅ Rahul
// echo $user->email; ❌ OK from child class only
// echo $user->password; ❌ Fatal Error — private!
var_dump($user->verifyPassword("pass123")); // true
?>

5
$this — Current Object Reference
$this — class के अंदर current object को refer करता है। Properties और methods access करने के लिए $this-> use करो। Method Chaining के साथ powerful।
$this — USAGE & METHOD CHAINING
<?php
class QueryBuilder {
  private string $table = "";
  private array $wheres = [];
  private int $limit = 100;

  public function from(string $table): static {
    $this->table = $table;
    return $this; // ← Method Chaining के लिए
  }

  public function where(string $condition): static {
    $this->wheres[] = $condition;
    return $this;
  }

  public function limit(int $n): static {
    $this->limit = $n;
    return $this;
  }

  public function build(): string {
    $sql = "SELECT * FROM {$this->table}";
    if ($this->wheres) {
      $sql .= " WHERE " . implode(" AND ", $this->wheres);
    }
    return $sql . " LIMIT {$this->limit}";
  }
}

// Method Chaining — fluent interface
$sql = (new QueryBuilder())
  ->from("users")
  ->where("active = 1")
  ->where("role = 'admin'")
  ->limit(10)
  ->build();
echo $sql;
// SELECT * FROM users WHERE active = 1 AND role = 'admin' LIMIT 10
?>

6
Getter और Setter — Controlled Access
Private properties को getter (read) और setter (write) methods से access करते हैं। Validation, transformation, readonly properties इसीसे बनते हैं।
GETTERS & SETTERS — WITH VALIDATION
<?php
class Product {
  private string $name;
  private float $price;
  private int $stock;

  public function __construct(string $name, float $price, int $stock) {
    $this->setName($name);
    $this->setPrice($price);
    $this->stock = $stock;
  }

  // Getter — read
  public function getName(): string { return $this->name; }
  public function getPrice(): float { return $this->price; }
  public function getStock(): int { return $this->stock; }

  // Setter — write + validate
  public function setName(string $name): void {
    if (strlen(trim($name)) < 2) {
      throw new InvalidArgumentException("Name too short");
    }
    $this->name = ucwords(trim($name));
  }

  public function setPrice(float $price): void {
    if ($price < 0) {
      throw new InvalidArgumentException("Price negative नहीं हो सकता");
    }
    $this->price = round($price, 2);
  }

  public function getPriceFormatted(): string {
    return "₹" . number_format($this->price, 2);
  }
}

$p = new Product("php book", 450.505, 10);
echo $p->getName(); // Php Book (ucwords)
echo $p->getPriceFormatted(); // ₹450.51 (rounded)
?>

7
Inheritance — extends से Class Inherit करना
👪
ext

extends keyword

Child class parent की सब public और protected properties और methods inherit करती है। Code reuse — parent में लिखो, सब children को मिलता है।

extends parent:: access Code Reuse
INHERITANCE — PARENT TO CHILD
<?php
// Parent Class
class Animal {
  public function __construct(
    protected string $naam,
    protected int $umar
  ) {}

  public function info(): string {
    return "{$this->naam}, {$this->umar} साल का";
  }

  public function sound(): string {
    return "...";
  }
}

// Child Class — Animal extend करो
class Dog extends Animal {
  private string $breed;

  public function __construct(string $naam, int $umar, string $breed) {
    parent::__construct($naam, $umar); // Parent constructor call
    $this->breed = $breed;
  }

  public function sound(): string { // Override!
    return "Woof! Woof!";
  }

  public function info(): string {
    return parent::info() . ", नस्ल: {$this->breed}"; // Parent method + extra
  }
}

class Cat extends Animal {
  public function sound(): string { return "Meow!"; }
}

$dog = new Dog("Tommy", 3, "Labrador");
$cat = new Cat("Whiskers", 2);

echo $dog->info(); // Tommy, 3 साल का, नस्ल: Labrador
echo $dog->sound(); // Woof! Woof!
echo $cat->sound(); // Meow!

// instanceof check
var_dump($dog instanceof Dog); // true
var_dump($dog instanceof Animal); // true! (is-a relationship)
?>
parent:: — Parent class की methods/constructor call करने के लिए। Child में constructor override करते समय parent::__construct() call करना न भूलो।

8
Method Overriding — Polymorphism
Child class parent की method को redefine करती है। Same method name, different behavior। Polymorphism — same interface, different implementations।
METHOD OVERRIDING — POLYMORPHISM
<?php
class Shape {
  public function area(): float {
    return 0.0; // Base implementation
  }
  public function describe(): string {
    return "Area: " . $this->area(); // Polymorphic call
  }
}

class Circle extends Shape {
  public function __construct(private float $radius) {}
  public function area(): float {
    return M_PI * $this->radius ** 2;
  }
}

class Rectangle extends Shape {
  public function __construct(
    private float $width,
    private float $height
  ) {}
  public function area(): float {
    return $this->width * $this->height;
  }
}

// Polymorphism — same interface, different results
$shapes = [
  new Circle(5),
  new Rectangle(4, 6),
  new Shape(),
];
foreach ($shapes as $shape) {
  echo get_class($shape) . ": " . round($shape->area(), 2) . "\n";
}
// Circle: 78.54
// Rectangle: 24
// Shape: 0
?>

9
Static Properties & Methods
static — Object बनाए बिना class directly access करने के लिए। ClassName::method() या self:: से। Utility functions, counters, singletons।
STATIC — PROPERTIES & METHODS
<?php
class Counter {
  private static int $count = 0; // सब objects share करते हैं

  public function __construct() {
    self::$count++; // static property access
  }

  public static function getCount(): int {
    return self::$count;
  }

  public static function reset(): void {
    self::$count = 0;
  }
}

new Counter(); new Counter(); new Counter();
echo Counter::getCount(); // 3 — Object बिना!

// Static Utility class
class Math {
  public static function percent(float $val, float $total): float {
    return $total ? round(($val / $total) * 100, 2) : 0;
  }
  public static function clamp(float $val, float $min, float $max): float {
    return max($min, min($max, $val));
  }
}

echo Math::percent(45, 60); // 75%
echo Math::clamp(150, 0, 100); // 100
?>

10
Abstract Class + Combined Real World Example
abstract class — directly instantiate नहीं हो सकती। Blueprint जो children को force करे कि वो specific methods implement करें।
ABSTRACT + COMBINED — Payment System
<?php
// Abstract — Payment gateway blueprint
abstract class PaymentGateway {
  protected float $amount;
  protected static int $transactionCount = 0;

  public function __construct(float $amount) {
    if ($amount <= 0) throw new InvalidArgumentException("Invalid amount");
    $this->amount = $amount;
  }

  // Abstract — हर child को implement करना पड़ेगा
  abstract public function charge(): bool;
  abstract public function getGatewayName(): string;

  // Concrete — सब children को मिलेगा
  public function process(): array {
    static::$transactionCount++;
    $success = $this->charge();
    return [
      "gateway" => $this->getGatewayName(),
      "amount" => $this->amount,
      "success" => $success,
      "txn_id" => $success ? "TXN" . time() : null,
    ];
  }

  public static function getTotalTransactions(): int {
    return static::$transactionCount;
  }
}

// Concrete implementations
class RazorpayGateway extends PaymentGateway {
  public function charge(): bool {
    // Razorpay API call here
    return true; // simulation
  }
  public function getGatewayName(): string { return "Razorpay"; }
}

class PaytmGateway extends PaymentGateway {
  public function charge(): bool { return true; }
  public function getGatewayName(): string { return "Paytm"; }
}

// Usage
$payments = [
  new RazorpayGateway(1299),
  new PaytmGateway(499),
];
foreach ($payments as $payment) {
  $result = $payment->process();
  echo "{$result['gateway']}: ₹{$result['amount']} — " . ($result["success"] ? "✅" : "❌") . "\n";
}
echo "Total: " . PaymentGateway::getTotalTransactions(); // 2
?>
OOP Pattern: Abstract class (blueprint) → extends (inherit) → override abstract methods → parent:: (reuse) → static (shared state)

Quick Reference — OOP Keywords
KeywordकामExample
classClass define करनाclass Student { }
newObject बनाना$s = new Student()
$thisCurrent object$this->naam
__construct()ConstructorAuto-called on new
__destruct()DestructorAuto-called on destroy
publicसब access कर सकेंpublic string $naam
protectedClass + childrenprotected float $price
privateसिर्फ classprivate string $pass
extendsInherit करनाclass Dog extends Animal
parent::Parent class accessparent::__construct()
staticClass-level (no object)static int $count
self::Current class staticself::$count++
abstractMust be implementedabstract function area()
instanceofObject type check$obj instanceof Dog
readonlyWrite-once property (PHP 8.1)readonly string $naam

निष्कर्ष

PHP OOP modern PHP development का foundation है। Laravel, Symfony — सब frameworks OOP पर based हैं। इन्हें सीखने से आप real projects बना सकते हो।

Class = Blueprint, Object = Instance। new keyword से object बनाते हैं।

__construct() — PHP 8 Promotion से shorter। Validation constructor में।

private/protected/public — Encapsulation। Getters/Setters से controlled access।

extends — Code reuse। parent:: से parent methods call। instanceof से type check।

static — Object बिना class-level access। Utility functions, counters।

abstract — Children को force करो कि methods implement करें।

$this->method() — Method chaining से fluent API।

🚀 अगला Chapter: Chapter 17: PHP Forms & Validation — $_POST/$_GET handle करना, CSRF protection, form validation, sanitization।