Paramclasses Academy - Blog

Tutorials Details

←
Post 13 of 15
→

What is Object-Oriented Programming (OOP) in PHP

What is Object-Oriented Programming (OOP) in PHP

October 16, 2026

Object-Oriented Programming (OOP) in PHP: Classes, Objects, Inheritance and Examples

Object-Oriented Programming (OOP) in PHP is a programming approach that organizes code using classes and objects. It helps developers build applications that are reusable, organized, and easier to maintain.

Instead of writing all application logic in a single file, developers can divide code into classes that represent different parts of an application.

For example, a student management system may contain separate classes for students, courses, teachers, and payments.

In this tutorial, you will learn PHP OOP concepts with simple explanations and practical examples.

What Is Object-Oriented Programming in PHP?

Object-Oriented Programming is a programming paradigm in which data and related behavior are grouped into objects.

An object contains:

  • Properties: Variables that store an object's data.

  • Methods: Functions defined inside a class that describe its behavior.

For example, a Student object may contain a student's name and course, along with a method to display the student's details.

Why Is OOP Used in PHP?

PHP OOP helps developers structure applications more effectively.

The main benefits are:

  • Code reusability: Reuse classes and methods where appropriate.

  • Maintainability: Keep related logic organized.

  • Encapsulation: Control access to internal data.

  • Inheritance: Extend existing classes.

  • Flexibility: Support different implementations through interfaces and polymorphism.

  • Scalability: Make complex applications easier to extend.

1. What Is a Class in PHP?

A class is a blueprint for creating objects. It defines the properties and methods that objects created from it can use.

Example: Creating a Class

<?php

class Student
{
    public string $name = "Rahul";
    public string $course = "PHP Development";

    public function showDetails(): void
    {
        echo "Name: " . $this->name . "<br>";
        echo "Course: " . $this->course;
    }
}

In this example:

  • class is the keyword used to declare a class.

  • Student is the class name.

  • $name and $course are properties.

  • showDetails() is a method.

  • $this refers to the current object.

A class describes what its objects contain and what they can do.

2. What Is an Object in PHP?

An object is an instance of a class. PHP uses the new keyword to create an object.

Example: Creating an Object

<?php

class Student
{
    public string $name = "Rahul";

    public function showName(): void
    {
        echo $this->name;
    }
}

$student = new Student();

$student->showName();

Output:

Rahul

Here, $student is an object of the Student class. The -> operator accesses the object's properties and methods.

Creating Multiple Objects

<?php

class Student
{
    public string $name;

    public function showName(): void
    {
        echo $this->name . "<br>";
    }
}

$student1 = new Student();
$student1->name = "Rahul";

$student2 = new Student();
$student2->name = "Priya";

$student1->showName();
$student2->showName();

Output:

Rahul
Priya

Each object can hold its own property values.

3. What Is a Constructor in PHP?

A constructor is a special method that runs automatically when an object is created. In PHP, the constructor method is named __construct().

It is commonly used to initialize object properties.

Example: Constructor in PHP

<?php

class Student
{
    public string $name;
    public string $course;

    public function __construct(string $name, string $course)
    {
        $this->name = $name;
        $this->course = $course;
    }

    public function showDetails(): void
    {
        echo "Name: " . $this->name . "<br>";
        echo "Course: " . $this->course;
    }
}

$student = new Student("Rahul", "PHP Development");

$student->showDetails();

Output:

Name: Rahul
Course: PHP Development

The constructor receives the name and course when the object is created and assigns them to its properties.

4. What Is Encapsulation in PHP?

Encapsulation means keeping an object's internal data protected and providing controlled ways to access or modify it.

PHP provides three main visibility keywords:

  • public: Accessible from anywhere the object or class is available.

  • protected: Accessible within the class and its subclasses.

  • private: Accessible only within the class that declares it.

Example: Encapsulation

<?php

class BankAccount
{
    private float $balance = 0;

    public function deposit(float $amount): void
    {
        if ($amount <= 0) {
            throw new InvalidArgumentException(
                "Amount must be greater than zero."
            );
        }

        $this->balance += $amount;
    }

    public function getBalance(): float
    {
        return $this->balance;
    }
}

$account = new BankAccount();

$account->deposit(5000);

echo $account->getBalance();

Output:

5000

The $balance property is private, so code outside the class cannot directly change it. The deposit() method controls how money is added.

This example demonstrates encapsulation; a real banking application would also need transaction handling, authorization, and other safeguards.

5. What Is Inheritance in PHP?

Inheritance allows a class to extend another class and reuse its accessible properties and methods.

The extends keyword is used to inherit from a class.

Example: Inheritance

<?php

class Animal
{
    public function eat(): void
    {
        echo "Animal is eating.<br>";
    }
}

class Dog extends Animal
{
    public function bark(): void
    {
        echo "Dog is barking.";
    }
}

$dog = new Dog();

$dog->eat();
$dog->bark();

Output:

Animal is eating.
Dog is barking.

The Dog class inherits the eat() method from the Animal class and also defines its own bark() method.

PHP supports single class inheritance, meaning a class can directly extend only one class.

6. What Is Polymorphism in PHP?

Polymorphism means that different classes can provide their own implementations of a common method or interface.

It helps developers write flexible code that can work with different object types.

Example: Polymorphism Using Inheritance

<?php

class Animal
{
    public function sound(): void
    {
        echo "Animal makes a sound.<br>";
    }
}

class Dog extends Animal
{
    public function sound(): void
    {
        echo "Dog barks.<br>";
    }
}

class Cat extends Animal
{
    public function sound(): void
    {
        echo "Cat meows.<br>";
    }
}

$animals = [
    new Dog(),
    new Cat()
];

foreach ($animals as $animal) {
    $animal->sound();
}

Output:

Dog barks.
Cat meows.

Both classes provide their own implementation of sound(). The loop can call the same method on different objects.

7. What Is Abstraction in PHP?

Abstraction means exposing essential behavior while hiding implementation details.

PHP supports abstraction through abstract classes and interfaces.

Example: Abstract Class

<?php

abstract class Payment
{
    abstract public function pay(float $amount): void;
}

class UpiPayment extends Payment
{
    public function pay(float $amount): void
    {
        echo "Processing UPI payment of " . $amount;
    }
}

$payment = new UpiPayment();

$payment->pay(1500);

Output:

Processing UPI payment of 1500

An abstract class cannot be instantiated directly. A concrete subclass must implement its abstract methods before it can be instantiated.

This example illustrates the structure of a payment system. Actual payment processing requires a secure integration with a payment provider.

8. What Is an Interface in PHP?

An interface defines a contract that implementing classes must follow. It specifies method signatures without providing their usual implementation.

The interface and implements keywords are used to define and implement interfaces.

Example: Interface in PHP

<?php

interface Notification
{
    public function send(string $message): void;
}

class EmailNotification implements Notification
{
    public function send(string $message): void
    {
        echo "Email notification: " . $message;
    }
}

class SmsNotification implements Notification
{
    public function send(string $message): void
    {
        echo "SMS notification: " . $message;
    }
}

function notifyUser(
    Notification $notification,
    string $message
): void {
    $notification->send($message);
}

notifyUser(
    new EmailNotification(),
    "Your account has been created."
);

Output:

Email notification: Your account has been created.

The notifyUser() function accepts any object that implements Notification. This makes it easier to add new notification types without changing the function's core logic.

9. What Is the static Keyword in PHP?

The static keyword can be used to define properties and methods that belong to the class rather than a particular object.

Static methods can be called using the class name and the :: operator.

Example: Static Method

<?php

class Calculator
{
    public static function add(int $a, int $b): int
    {
        return $a + $b;
    }
}

echo Calculator::add(10, 20);

Output:

30

Here, add() is a static method, so you do not need to create a Calculator object to call it.

Use static members when behavior or data genuinely belongs to the class rather than an individual object.

10. What Is the final Keyword in PHP?

The final keyword prevents a class from being extended or a method from being overridden.

Example: Final Method

<?php

class User
{
    final public function getRole(): string
    {
        return "User";
    }
}

class Admin extends User
{
    // Overriding getRole() here would cause an error.
}

The getRole() method cannot be overridden in a subclass because it is declared final.

A class can also be declared final to prevent inheritance entirely.

11. What Is a Destructor in PHP?

A destructor is a special method named __destruct(). PHP calls it when an object is being destroyed or during script shutdown, subject to the object's lifecycle.

Example: Destructor

<?php

class Demo
{
    public function __construct()
    {
        echo "Object created.<br>";
    }

    public function __destruct()
    {
        echo "Object cleanup.";
    }
}

$demo = new Demo();

Possible output:

Object created.
Object cleanup.

Destructors can be useful for cleanup tasks, but they should not be relied on for time-critical operations or guaranteed execution at a particular moment.

12. Practical Example: Student Management Using OOP

The following example combines classes, properties, a constructor, and methods.

<?php

class Student
{
    private string $name;
    private string $course;
    private float $fees;

    public function __construct(
        string $name,
        string $course,
        float $fees
    ) {
        $this->name = $name;
        $this->course = $course;
        $this->fees = $fees;
    }

    public function getDetails(): array
    {
        return [
            'name' => $this->name,
            'course' => $this->course,
            'fees' => $this->fees,
        ];
    }
}

$student = new Student(
    "Rahul",
    "PHP Development",
    5000
);

$details = $student->getDetails();

echo "Student Name: " .
    htmlspecialchars($details['name'], ENT_QUOTES, 'UTF-8') .
    "<br>";

echo "Course: " .
    htmlspecialchars($details['course'], ENT_QUOTES, 'UTF-8') .
    "<br>";

echo "Fees: " . $details['fees'];

Output:

Student Name: Rahul
Course: PHP Development
Fees: 5000

This example keeps the student's data private and exposes it through a method. In a larger project, you could extend this structure with validation, database storage, and separate classes for managing multiple students.

PHP OOP Concepts: Quick Revision

Concept Meaning
Class Blueprint for creating objects
Object Instance of a class
Property Data stored in an object or class
Method Function defined inside a class
Constructor Initializes an object
Encapsulation Controls access to internal data
Inheritance Extends an existing class
Polymorphism Supports different implementations of common behavior
Abstraction Exposes essential behavior while hiding details
Interface Defines a contract for implementing classes
Static Defines class-level properties or methods
Final Prevents class extension or method overriding

Best Practices for PHP OOP

  • Give classes and methods meaningful names.

  • Keep each class focused on a clear responsibility.

  • Use private or protected when public access is unnecessary.

  • Prefer composition over inheritance when it produces a simpler design.

  • Use interfaces when multiple implementations need a shared contract.

  • Validate input and handle exceptions appropriately.

  • Separate application logic from presentation code.

  • Follow PSR coding standards for consistent PHP code.

Frequently Asked Questions (FAQs)

1. What is OOP in PHP?

OOP is a programming approach that organizes code into classes and objects containing properties and methods.

2. What is the difference between a class and an object in PHP?

A class defines the structure and behavior, while an object is an instance created from that class.

3. What is the use of $this in PHP?

$this refers to the current object and is used to access its non-static properties and methods.

4. What are the four main principles of OOP?

The four commonly taught principles are encapsulation, inheritance, polymorphism, and abstraction.

5. Does PHP support multiple inheritance?

PHP does not support extending multiple classes directly. However, a class can implement multiple interfaces and use multiple traits.

6. Is PHP OOP useful for web development?

Yes. OOP is useful for organizing reusable code in applications such as e-commerce websites, student management systems, hotel management systems, and content management systems.

Conclusion

Object-Oriented Programming in PHP helps developers build structured, reusable, and maintainable applications. Understanding classes, objects, constructors, encapsulation, inheritance, polymorphism, abstraction, and interfaces provides a strong foundation for professional PHP development.

Practice these concepts by creating small classes first, then apply them to a larger project such as a student management system. Once you understand PHP OOP, you will also be better prepared to learn frameworks such as CodeIgniter and Laravel.

←
Post 13 of 15
→