Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

3. Object Oriented Features

Lesson 23 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

Object-Oriented Programming (OOP) in PHP: Core Concepts

Study Deep: The S.O.L.I.D. Principles

For advanced students, understanding SOLID principles is essential for writing clean, maintainable OOP code.

  1. S - Single Responsibility: A class should have only one reason to change.
  2. O - Open/Closed: Software entities should be open for extension but closed for modification.
  3. L - Liskov Substitution: Objects of a superclass should be replaceable with objects of its subclasses.
  4. I - Interface Segregation: Clients should not be forced to depend on methods they do not use.
  5. D - Dependency Inversion: Depend on abstractions, not concretions.

1. What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. An object is a software entity that bundles together related data (called properties or attributes) and behavior (called methods).

Real-World Analogy: Think of a "Car" as a class:

  • Properties (Data): color, model, speed, fuelLevel
  • Methods (Behavior): accelerate(), brake(), refuel(), honk()
  • Every specific car (a Red Tesla, a Blue Honda) is an object — a specific instance of the Car class.

2. OOP vs. Procedural Programming

FeatureProcedural ProgrammingObject-Oriented Programming
FocusFunctions and sequential logicObjects that contain both data and behavior
StructureCode organized into procedures/functionsCode organized into Classes
DataData is separate from functions; often globalData is encapsulated inside objects
ReusabilityFunctions can be reused, but limitedHighly reusable via Inheritance and Objects
ScalabilityBecomes harder to manage as app growsScales much better for large applications
SecurityData can be freely modified from anywhereAccess modifiers restrict data access
Real-World ModelingDifficultNatural (objects map to real-world entities)

3. Four Pillars of OOP

PillarDefinitionPHP Keyword/Concept
EncapsulationBundling data + methods, restricting direct access from outsideprivate, protected, getters/setters
InheritanceA child class acquires properties and methods from a parent classextends keyword
PolymorphismOne interface, many implementations. Objects of different classes respond to the same method call differently.Method Overriding
AbstractionHiding complex implementation details and exposing only necessary featuresabstract classes, Interfaces

4. Key OOP Terminology

TermDefinition
ClassA blueprint or template that defines the structure (properties + methods) for objects
ObjectA specific instance created from a class; occupies actual memory
PropertyA variable defined inside a class; represents the state or attributes of an object
MethodA function defined inside a class; represents the behavior of an object
ConstructorA special method (__construct) auto-called when an object is created; initializes properties
DestructorA special method (__destruct) auto-called when an object is destroyed or script ends; cleanup
$thisA special keyword inside a class that refers to the current object instance
InstantiationThe act of creating an object from a class using the new keyword

5. Defining a Class and Creating Objects

<?php
// Class definition
class Student {
  // Properties (attributes)
  public $name;
  public $rollNo;
  public $course;

  // Method (behavior)
  public function displayInfo() {
    echo "Name: {$this->name}, Roll No: {$this->rollNo}, Course: {$this->course}<br>";
  }
}

// Creating objects (instantiation)
$s1 = new Student();
$s1->name   = "Rohit";
$s1->rollNo = 101;
$s1->course = "BCA";
$s1->displayInfo(); // Output: Name: Rohit, Roll No: 101, Course: BCA

$s2 = new Student();
$s2->name   = "Priya";
$s2->rollNo = 102;
$s2->course = "BCA";
$s2->displayInfo(); // Output: Name: Priya, Roll No: 102, Course: BCA
?>

6. The $this Keyword

The $this keyword refers to the current object on which a method is called. It is used inside class methods to access the object's own properties and methods.

class Rectangle {
  public $width;
  public $height;

  public function setDimensions($w, $h) {
    $this->width  = $w; // 'this' refers to the calling rectangle object
    $this->height = $h;
  }

  public function getArea() {
    return $this->width * $this->height;
  }
}

$rect = new Rectangle();
$rect->setDimensions(10, 5);
echo "Area: " . $rect->getArea(); // Output: Area: 50

7. Constructor and Destructor

Constructor (__construct): A constructor is a special method that PHP automatically calls as soon as an object is created with new. Its primary purpose is to initialize the object's properties with default or provided values — eliminating the need to set them one by one after creation.

Destructor (__destruct): A destructor is called automatically when the object goes out of scope or the script ends. It is used for cleanup tasks like closing file handles or database connections.

class BankAccount {
  public $owner;
  public $balance;

  // Constructor: called automatically when object is created
  public function __construct($owner, $balance = 0) {
    $this->owner   = $owner;
    $this->balance = $balance;
    echo "Account created for {$this->owner}<br>";
  }

  public function deposit($amount) {
    $this->balance += $amount;
    echo "Deposited ₹{$amount}. Balance: ₹{$this->balance}<br>";
  }

  // Destructor: called when object is destroyed or script ends
  public function __destruct() {
    echo "Account session for {$this->owner} closed.<br>";
  }
}

$acc = new BankAccount("Rohit", 1000); // Constructor is called
$acc->deposit(500);
// At script end: Destructor is called automatically

Output:

Account created for Rohit
Deposited ₹500. Balance: ₹1500
Account session for Rohit closed.