PHP OOP — Object Oriented
Programming in Hindi
PHP OOP की पूरी जानकारी — Class, Object, Constructor, Destructor, Properties, Methods, Access Modifiers, Inheritance, static, abstract। Real World examples के साथ।
📋 इस Article में क्या-क्या है
- OOP क्या है? — Why?
- Class और Object
- Properties और Methods
- Constructor और Destructor
- Access Modifiers
- $this keyword
- Getter और Setter
- Inheritance — extends
- Method Overriding
- Static Properties & Methods
Object Oriented Programming (OOP) — Code को real-world objects की तरह organize करना। Student, Product, Order — हर चीज़ एक Object है जिसकी properties और behaviors होती हैं।
❌ Procedural Style — Functions scattered
$studentNaam = "Rahul";
$studentMarks = 95;
function getGrade($marks) { ... }
function printReport($naam, $marks) { ... }
✅ OOP Style — Data + Methods एक साथ
$student = new Student("Rahul", 95);
echo $student->getGrade();
$student->printReport();
| OOP Concept | Real World | PHP |
|---|---|---|
| Class | Car का blueprint/design | class Car { } |
| Object | Actual car (मेरी Maruti) | $myCar = new Car() |
| Property | Car का color, speed | $this->color = "red" |
| Method | Car का start(), stop() | public function start() |
| Constructor | Car factory में assemble | __construct() |
| Inheritance | ElectricCar is a Car | class ElectricCar extends Car |
// Properties (variables)
public string $naam;
// Methods (functions)
public function greet(): string {
return "Hello!";
}
}
// Object बनाना
$obj = new ClassName();
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
?>
// 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}";
}
}
?>
| Modifier | Same Class | Child Class | Outside | Use Case |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | API, getters, public methods |
| protected | ✅ | ✅ | ❌ | Inheritance में reuse |
| private | ✅ | ❌ | ❌ | Internal state, sensitive data |
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
?>
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
?>
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)
?>
// 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)
?>
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
?>
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
?>
// 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
?>
| Keyword | काम | Example |
|---|---|---|
| class | Class define करना | class Student { } |
| new | Object बनाना | $s = new Student() |
| $this | Current object | $this->naam |
| __construct() | Constructor | Auto-called on new |
| __destruct() | Destructor | Auto-called on destroy |
| public | सब access कर सकें | public string $naam |
| protected | Class + children | protected float $price |
| private | सिर्फ class | private string $pass |
| extends | Inherit करना | class Dog extends Animal |
| parent:: | Parent class access | parent::__construct() |
| static | Class-level (no object) | static int $count |
| self:: | Current class static | self::$count++ |
| abstract | Must be implemented | abstract function area() |
| instanceof | Object type check | $obj instanceof Dog |
| readonly | Write-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।