PHP OOP का पूरा नाम PHP Object-Oriented Programming है। यह PHP में code को classes और objects के रूप में organize करने का तरीका है।
अगर आप PHP में बड़े applications, APIs, e-commerce websites या frameworks जैसे Symfony और Laravel पर काम करना चाहते हैं, तो OOP समझना बहुत जरूरी है।
इस guide में हम PHP OOP के सभी important concepts को आसान Hinglish और practical code examples के साथ सीखेंगे।
1. What is OOP in PHP?#
OOP यानी Object-Oriented Programming एक programming approach है जिसमें हम code को Objects और Classes के आधार पर organize करते हैं।
Procedural programming में हम functions और instructions के आधार पर code लिखते हैं, जबकि OOP में हम related data और functionality को एक class के अंदर organize कर सकते हैं।
Real-world example
मान लीजिए आपको एक Car बनानी है।
एक car में कुछ properties होती हैं:
- Brand
- Color
- Model
- Speed
और कुछ actions होते हैं:
- Start
- Stop
- Accelerate
- Brake
OOP में हम इन properties और actions को एक class में define कर सकते हैं।
Why use OOP?
- Code को reusable बनाना।
- Large applications को organize करना।
- Code maintenance आसान करना।
- Data और functionality को एक जगह रखना।
- Inheritance के माध्यम से code reuse करना।
- Complex applications को छोटे components में divide करना।
2. Class and Object#
PHP OOP का सबसे basic concept Class और Object है।
What is a Class?
Class एक blueprint या template है जिसके आधार पर objects बनाए जाते हैं।
What is an Object?
Object किसी class का actual instance होता है।
इसे ऐसे समझिए:
- Class = Car का design
- Object = Actual Car
Example: Create a Class
<?php
class Car
{
public $brand = "Toyota";
public $color = "Black";
public function start()
{
return "Car started!";
}
}
// Create an object
$car = new Car();
// Access properties
echo $car->brand;
// Call method
echo $car->start();
?>Important points:
classkeyword से class बनती है।newkeyword से object create होता है।->operator से object की properties और methods access करते हैं।- Class के अंदर defined variables को properties कहते हैं।
- Class के अंदर defined functions को methods कहते हैं।
3. Properties and Methods#
Properties
Properties किसी object का data या state store करती हैं।
<?php
class Student
{
public $name = "Rahul";
public $age = 22;
public $course = "PHP";
}
$student = new Student();
echo $student->name;
echo $student->age;
?>Methods
Methods class के अंदर define किए गए functions होते हैं।
<?php
class Calculator
{
public function add($a, $b)
{
return $a + $b;
}
public function subtract($a, $b)
{
return $a - $b;
}
}
$calculator = new Calculator();
echo $calculator->add(10, 20);
echo $calculator->subtract(20, 5);
?>4. Constructor in PHP#
Constructor एक special method है जो object create होते समय automatically call होता है।
PHP में constructor का नाम __construct() होता है।
इसका उपयोग object initialize करने के लिए किया जाता है।
Example
<?php
class User
{
public $name;
public $email;
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
public function getDetails()
{
return $this->name . " - " . $this->email;
}
}
$user = new User("Rahul", "rahul@example.com");
echo $user->getDetails();
?>Output:
Rahul - rahul@example.comWhat is $this?
$this current object को refer करता है।
उदाहरण:
$this->name = $name;यहाँ:
$this->name= Current object की property$name= Constructor का parameter
याद रखें: $this को non-static methods और object context में use किया जाता है।
5. Access Modifiers in PHP#
Access modifiers यह control करते हैं कि class की properties और methods को कहाँ से access किया जा सकता है।
PHP में तीन main access modifiers हैं:
| Modifier | Access |
|---|---|
| public | कहीं से भी access किया जा सकता है |
| protected | Class और उसकी child classes के अंदर |
| private | केवल उसी class के अंदर |
Public Example
<?php
class User
{
public $name = "Rahul";
}
$user = new User();
echo $user->name;
?>Protected Example
<?php
class ParentClass
{
protected $message = "Hello";
}
class ChildClass extends ParentClass
{
public function showMessage()
{
return $this->message;
}
}
$child = new ChildClass();
echo $child->showMessage();
?>Private Example
<?php
class BankAccount
{
private $balance = 5000;
public function getBalance()
{
return $this->balance;
}
}
$account = new BankAccount();
echo $account->getBalance();
// Direct access is not allowed:
// echo $account->balance;
?>Important: Private property को directly class के बाहर access नहीं कर सकते। इसके लिए public methods का उपयोग किया जा सकता है।
6. The Four Pillars of OOP#
OOP के चार मुख्य concepts होते हैं:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
इन चार concepts को समझना PHP OOP सीखने के लिए बहुत जरूरी है।
7. Encapsulation#
Encapsulation का मतलब है data और उससे संबंधित methods को एक class में bundle करना और access को control करना।
Simple words में, हम sensitive properties को private या protected रख सकते हैं और उन्हें controlled methods के माध्यम से access या update कर सकते हैं।
Example
<?php
class BankAccount
{
private $balance = 0;
public function deposit($amount)
{
if ($amount > 0) {
$this->balance += $amount;
}
}
public function getBalance()
{
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(1000);
echo $account->getBalance();
?>Output:
1000यहाँ balance private है। इसे सीधे update नहीं किया जा सकता। Deposit method के माध्यम से controlled update किया जाता है।
Real-world use: Banking systems, user accounts, payment systems और sensitive data management।
8. Inheritance#
Inheritance का मतलब है एक class दूसरी class की properties और methods को inherit कर सकती है।
इससे code reuse करना आसान होता है।
- Parent Class: जिस class से inherit किया जाता है।
- Child Class: जो दूसरी class को inherit करती है।
extends: Inheritance के लिए उपयोग होने वाला keyword।
Example
<?php
class Animal
{
public function eat()
{
return "Animal is eating";
}
}
class Dog extends Animal
{
public function bark()
{
return "Dog is barking";
}
}
$dog = new Dog();
echo $dog->eat();
echo $dog->bark();
?>यहाँ Dog class ने Animal class का eat() method inherit किया है।
Method Overriding
जब child class parent class के method को अपने implementation से redefine करती है, तो इसे method overriding कहते हैं।
<?php
class Animal
{
public function sound()
{
return "Animal makes a sound";
}
}
class Dog extends Animal
{
public function sound()
{
return "Dog barks";
}
}
$dog = new Dog();
echo $dog->sound();
?>Output:
Dog barksParent Keyword
Child class के अंदर parent class के method को call करने के लिए parent:: का उपयोग किया जाता है।
<?php
class ParentClass
{
public function show()
{
return "Parent method";
}
}
class ChildClass extends ParentClass
{
public function show()
{
return parent::show() . " and Child method";
}
}
$obj = new ChildClass();
echo $obj->show();
?>9. Polymorphism#
Polymorphism का अर्थ है एक common interface या method के माध्यम से अलग-अलग implementations को use करना।
Simple words में, same method name अलग-अलग classes में अलग behavior दे सकता है।
Example: Interface-based Polymorphism
<?php
interface Payment
{
public function pay($amount);
}
class CreditCard implements Payment
{
public function pay($amount)
{
return "Paid $amount using Credit Card";
}
}
class UPI implements Payment
{
public function pay($amount)
{
return "Paid $amount using UPI";
}
}
function processPayment(Payment $payment, $amount)
{
echo $payment->pay($amount);
}
processPayment(new CreditCard(), 1000);
processPayment(new UPI(), 500);
?>यहाँ processPayment() अलग-अलग payment classes के objects के साथ काम कर सकता है।
Real-world use: Payment gateways, notification systems, shipping methods और different database drivers।
10. Abstraction#
Abstraction का मतलब है implementation की unnecessary details को hide करना और केवल जरूरी functionality expose करना।
PHP में abstraction के लिए abstract classes और interfaces का उपयोग किया जाता है।
Abstract Class
Abstract class को directly instantiate नहीं किया जा सकता।
इसमें abstract methods और normal methods दोनों हो सकते हैं।
Abstract method केवल declaration define करता है। Child class को उसका implementation देना होता है।
Example
<?php
abstract class Shape
{
abstract public function calculateArea();
public function description()
{
return "This is a shape";
}
}
class Circle extends Shape
{
private $radius;
public function __construct($radius)
{
$this->radius = $radius;
}
public function calculateArea()
{
return pi() * $this->radius * $this->radius;
}
}
$circle = new Circle(5);
echo $circle->calculateArea();
?>Important: Abstract class का object directly create नहीं कर सकते। इसकी child class को required abstract methods implement करने होते हैं।
11. Interface in PHP#
Interface एक contract की तरह काम करता है।
यह define करता है कि implementing class में कौन-से methods होने चाहिए।
Interface declare करने के लिए interface keyword और implement करने के लिए implements keyword का उपयोग होता है।
Example
<?php
interface Logger
{
public function log($message);
}
class FileLogger implements Logger
{
public function log($message)
{
return "Logging message: " . $message;
}
}
$logger = new FileLogger();
echo $logger->log("User logged in");
?>Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract class | interface |
| Object creation | Directly नहीं | Directly नहीं |
| Methods | Abstract और normal methods | Method contracts |
| Properties | Normal properties allowed | Constants allowed |
| Constructor | हो सकता है | Constructor declaration नहीं |
| Inheritance | एक parent class extend | Multiple interfaces implement कर सकते हैं |
| Use case | Shared base functionality | Common contract |
याद रखें: एक class केवल एक class को extend कर सकती है, लेकिन multiple interfaces implement कर सकती है।
12. Static Properties and Methods#
Static properties और methods class से संबंधित होते हैं, किसी particular object से नहीं।
इन्हें access करने के लिए :: (Scope Resolution Operator) का उपयोग किया जाता है।
Example
<?php
class MathHelper
{
public static $pi = 3.14159;
public static function square($number)
{
return $number * $number;
}
}
echo MathHelper::$pi;
echo MathHelper::square(5);
?>Important:
- Static property:
ClassName::$property - Static method:
ClassName::method() - Static method के अंदर
$thisavailable नहीं होता।
13. Constants in Classes#
Class constants ऐसी values होती हैं जिन्हें class के अंदर define किया जाता है और बाद में change नहीं किया जा सकता।
Example
<?php
class AppConfig
{
public const APP_NAME = "TheEasyMaster";
public const VERSION = "1.0";
}
echo AppConfig::APP_NAME;
?>Class constants को :: operator से access किया जाता है।
14. Traits in PHP#
PHP में एक class केवल एक parent class extend कर सकती है। लेकिन traits की मदद से multiple classes में common methods reuse किए जा सकते हैं।
Trait declare करने के लिए trait और use करने के लिए use keyword का उपयोग होता है।
Example
<?php
trait Logger
{
public function log($message)
{
echo "[LOG]: " . $message;
}
}
class User
{
use Logger;
}
class Order
{
use Logger;
}
$user = new User();
$user->log("User created");
?>यहाँ User और Order दोनों classes Logger trait का method reuse कर सकती हैं।
Real-world use: Logging, common utility methods और reusable functionality।
15. Final Keyword#
final keyword का उपयोग inheritance या method overriding को रोकने के लिए किया जाता है।
Final Class
Final class को extend नहीं किया जा सकता।
<?php
final class Security
{
public function check()
{
return "Security check";
}
}
// This is not allowed:
// class CustomSecurity extends Security {}
?>Final Method
Final method को child class में override नहीं किया जा सकता।
<?php
class ParentClass
{
final public function show()
{
return "This method cannot be overridden";
}
}
?>16. Constructor Property Promotion#
PHP 8.0 से constructor property promotion available है।
इससे constructor parameters के माध्यम से properties declare और initialize करना आसान हो जाता है।
Traditional Approach
<?php
class Product
{
private string $name;
private float $price;
public function __construct(string $name, float $price)
{
$this->name = $name;
$this->price = $price;
}
}
?>Constructor Property Promotion
<?php
class Product
{
public function __construct(
private string $name,
private float $price
) {
}
}
?>दोनों approaches में properties initialize होती हैं। दूसरी approach में कम code लिखना पड़ता है।
17. Type Declarations and Return Types#
PHP में properties, parameters और return values के लिए types declare किए जा सकते हैं।
Example
<?php
class Calculator
{
public function add(int $a, int $b): int
{
return $a + $b;
}
}
$calculator = new Calculator();
echo $calculator->add(10, 20);
?>Common Type Declarations
| Type | Meaning |
|---|---|
| int | Integer number |
| float | Decimal number |
| string | Text |
| bool | true / false |
| array | Array |
| object | Object |
| mixed | Any type |
| void | No return value |
| ?string | String or null |
Tip: Type declarations code को predictable और maintainable बनाने में मदद करते हैं।
18. Namespaces in PHP#
Namespaces का उपयोग classes, interfaces, functions और constants को organize करने और naming conflicts से बचने के लिए किया जाता है।
Example
<?php
namespace App\Services;
class UserService
{
public function getUser()
{
return "User data";
}
}
?>दूसरी file में इसे import करने के लिए:
<?php
use App\Services\UserService;
$service = new UserService();
echo $service->getUser();
?>Real-world use: Symfony, Laravel और Composer-based applications में namespaces बहुत important हैं।
19. Magic Methods in PHP#
Magic methods ऐसे special methods हैं जिनके नाम double underscore (__) से शुरू होते हैं।
PHP कुछ specific situations में इन्हें automatically call करता है।
| Magic Method | Purpose |
|---|---|
__construct() | Object create होने पर |
__destruct() | Object destroy होने पर |
__get() | Inaccessible property read करने पर |
__set() | Inaccessible property assign करने पर |
__call() | Inaccessible object method call होने पर |
__toString() | Object को string में convert करने पर |
__clone() | Object clone होने पर |
Example: __toString()
<?php
class User
{
public function __toString(): string
{
return "TheEasyMaster User";
}
}
$user = new User();
echo $user;
?>Output:
TheEasyMaster UserMagic methods का उपयोग सोच-समझकर करें। हर problem के लिए magic methods जरूरी नहीं होते।
20. Object Cloning#
PHP में किसी existing object की copy बनाने के लिए clone keyword का उपयोग किया जाता है।
Example
<?php
class User
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
$user1 = new User("Rahul");
$user2 = clone $user1;
$user2->name = "Amit";
echo $user1->name;
echo $user2->name;
?>Output:
Rahul
Amitclone default रूप से shallow copy बनाता है। अगर object के अंदर दूसरे objects हैं और उन्हें भी अलग copy करना है, तो __clone() में additional logic लिखना पड़ सकता है।
21. Dependency Injection (DI)#
Dependency Injection एक design technique है जिसमें किसी class को उसकी required dependencies खुद create करने के बजाय बाहर से provide की जाती हैं।
Simple words में, class को जिस service की जरूरत है, वह service constructor या method के माध्यम से दी जाती है।
Without Dependency Injection
<?php
class EmailService
{
public function send()
{
return "Email sent";
}
}
class UserController
{
public function notify()
{
$email = new EmailService();
return $email->send();
}
}
?>यहाँ UserController खुद EmailService create कर रहा है।
With Constructor Injection
<?php
class EmailService
{
public function send()
{
return "Email sent";
}
}
class UserController
{
private EmailService $emailService;
public function __construct(EmailService $emailService)
{
$this->emailService = $emailService;
}
public function notify()
{
return $this->emailService->send();
}
}
$email = new EmailService();
$controller = new UserController($email);
echo $controller->notify();
?>Benefits of Dependency Injection
- Classes के बीच tight coupling कम होती है।
- Unit testing आसान होती है।
- Code reusable बनता है।
- Dependencies को replace करना आसान होता है।
Real-world use: Symfony और Laravel में Dependency Injection बहुत important concept है।
22. Composition vs Inheritance#
Inheritance में एक class दूसरी class से functionality inherit करती है।
Composition में एक class दूसरी class के object को use करके functionality प्राप्त करती है।
Composition Example
<?php
class Engine
{
public function start()
{
return "Engine started";
}
}
class Car
{
private Engine $engine;
public function __construct(Engine $engine)
{
$this->engine = $engine;
}
public function startCar()
{
return $this->engine->start();
}
}
$car = new Car(new Engine());
echo $car->startCar();
?>Difference
| Inheritance | Composition |
|---|---|
| IS-A relationship | HAS-A relationship |
extends use होता है | Object dependency use होती है |
| Parent functionality inherit होती है | दूसरे object की functionality use होती है |
| Parent-child relationship | Independent components |
Best practice: केवल code reuse के लिए inheritance का उपयोग न करें। जहाँ suitable हो, composition को prefer करें।
23. SOLID Principles (Introduction)#
SOLID पाँच important object-oriented design principles का group है।
| Principle | Full Form | Simple Meaning |
|---|---|---|
| S | Single Responsibility | Class की एक clear responsibility हो |
| O | Open/Closed | Extension के लिए open, modification के लिए closed |
| L | Liskov Substitution | Child class parent की जगह सही तरीके से काम कर सके |
| I | Interface Segregation | छोटे और specific interfaces बनाएं |
| D | Dependency Inversion | High-level modules abstractions पर depend करें |
ये principles maintainable और scalable applications बनाने में मदद करते हैं।
24. Common PHP OOP Mistakes#
| Mistake | Better Approach |
|---|---|
| सभी properties public रखना | Proper access modifiers use करें |
| एक class में बहुत ज्यादा responsibilities रखना | Classes को responsibility के आधार पर divide करें |
| हर जगह inheritance use करना | जरूरत के अनुसार composition use करें |
| Constructor में unnecessary heavy logic रखना | Initialization को simple रखें |
| Dependencies खुद create करना | Dependency Injection अपनाएं |
| Interfaces का गलत उपयोग | Clear contracts define करें |
| बिना जरूरत magic methods use करना | Explicit methods prefer करें |
| बहुत बड़ी classes बनाना | Single Responsibility Principle follow करें |
25. PHP OOP Best Practices#
- Class और method के meaningful names रखें।
- Properties को जरूरत के अनुसार
privateयाprotectedरखें। - Type declarations और return types use करें।
- हर class की responsibility clear रखें।
- Code duplication से बचें।
- Interfaces का उपयोग करके loose coupling रखें।
- Dependency Injection को समझें और use करें।
- SOLID principles follow करें।
- Unit tests लिखें।
- PSR coding standards follow करें।
26. PHP OOP Quick Reference#
| Concept | Syntax |
|---|---|
| Class | class User {} |
| Object | $user = new User(); |
| Property | $this->name |
| Method | $user->getName() |
| Constructor | __construct() |
| Inheritance | class Child extends ParentClass |
| Interface | interface Payment {} |
| Implement | class UPI implements Payment |
| Abstract Class | abstract class Shape {} |
| Static Method | ClassName::method() |
| Constant | ClassName::CONSTANT |
| Trait | trait Logger {} |
| Use Trait | use Logger; |
| Parent Method | parent::method() |
| Object Clone | $copy = clone $object; |
| Namespace | namespace App\Services; |
| Dependency Injection | Constructor में dependency pass करना |
27. PHP OOP Interview Questions#
Q1. What is OOP in PHP?
OOP एक programming approach है जिसमें code को classes और objects के आधार पर organize किया जाता है।
Q2. What is the difference between class and object?
Class एक blueprint है, जबकि object उस class का actual instance है।
Q3. What are the four pillars of OOP?
Encapsulation, Inheritance, Polymorphism और Abstraction।
Q4. What is a constructor in PHP?
Constructor एक special method है जो object create होते समय automatically call होता है।
Q5. What is $this in PHP?
$this current object को refer करता है।
Q6. What is the difference between public, protected and private?
Public को कहीं से access किया जा सकता है, protected को class और child classes में, और private को केवल उसी class में access किया जा सकता है।
Q7. What is inheritance?
Inheritance में child class parent class की accessible properties और methods को inherit करती है।
Q8. What is method overriding?
जब child class parent class के method को अपने implementation से redefine करती है, तो उसे method overriding कहते हैं।
Q9. What is the difference between abstract class and interface?
Abstract class में abstract और normal methods हो सकते हैं। Interface मुख्य रूप से classes के लिए method contracts define करता है।
Q10. What is a trait in PHP?
Trait reusable methods का group है जिसे multiple classes में use किया जा सकता है।
Q11. What is dependency injection?
Dependency Injection में class की required dependencies बाहर से provide की जाती हैं।
Q12. What is the difference between self:: and $this->?
self:: current class के static members और class-level members को refer करने के लिए उपयोग होता है। $this-> current object की properties और methods access करने के लिए उपयोग होता है।
Q13. Can PHP support multiple inheritance?
PHP classes में multiple class inheritance support नहीं है। लेकिन एक class multiple interfaces implement कर सकती है और multiple traits use कर सकती है।
Q14. What is polymorphism?
Polymorphism में common contract या method के माध्यम से अलग-अलग implementations के साथ काम किया जा सकता है।
Q15. What is composition?
Composition में एक class दूसरे class के object को use करके functionality प्राप्त करती है।
28. Practice Exercises#
इन exercises को खुद code करके समझने की कोशिश करें।
Beginner Level
Studentनाम की class बनाएं जिसमें name, age और course properties हों।Calculatorclass बनाएं जिसमें add, subtract, multiply और divide methods हों।- Constructor का उपयोग करके
Productobject initialize करें।
Intermediate Level
Animalparent class बनाएं औरDogतथाCatchild classes बनाएं।BankAccountclass बनाएं जिसमें private balance और deposit/withdraw methods हों।Paymentinterface बनाकर UPI और CreditCard classes implement करें।
Advanced Level
- Logger trait बनाएं और उसे दो अलग classes में use करें।
- Constructor Injection के साथ UserController और EmailService बनाएं।
- एक छोटा e-commerce product management system बनाएं जिसमें Product, Category और Order classes हों।
29. Summary#
PHP OOP आपको structured, reusable और maintainable code लिखने में मदद करता है।
इस guide में आपने सीखा:
- Classes और Objects
- Properties और Methods
- Constructors और
$this - Access Modifiers
- Encapsulation और Inheritance
- Polymorphism और Abstraction
- Interfaces और Traits
- Static Methods और Constants
- Namespaces और Magic Methods
- Dependency Injection
- Composition और SOLID Principles
अगर आप PHP developer बनना चाहते हैं या Symfony और Laravel जैसे frameworks पर काम करना चाहते हैं, तो PHP OOP की अच्छी understanding जरूरी है।
Official References#
- PHP Manual – Classes and Objects
- PHP Manual – Object Interfaces
- PHP Manual – Traits
- PHP Manual – Namespaces
- PHP Manual – Constructors and Destructors
Practice Tip: केवल examples पढ़ने से OOP clear नहीं होगा। हर example को अपने local PHP environment में run करें और फिर उसमें छोटे changes करके देखें कि output कैसे बदलता है।