Lesson 46 of 50 – Object-Oriented PHP
92%

Object-Oriented PHP (OOP)

Object-Oriented Programming (OOP) is a programming approach that organizes code using classes and objects. PHP supports OOP features such as encapsulation, inheritance, polymorphism, and abstraction.

OOP helps developers organize large applications into reusable components, making projects such as student management systems, library management systems, and fee management systems easier to maintain.

1. What Is Object-Oriented Programming?

Object-Oriented Programming organizes related data and behavior into objects.

Important OOP concepts:

  • Class: A blueprint for creating objects.
  • Object: An instance of a class.
  • Property: A variable that belongs to a class or object.
  • Method: A function defined inside a class.
  • Constructor: A special method that runs when an object is created.
  • Inheritance: A class can inherit accessible features from another class.
  • Encapsulation: Controlling access to an object's data and behavior.
  • Polymorphism: Allowing different objects to provide different implementations of a common interface or inherited method.
  • Abstraction: Defining essential behavior while hiding implementation details.

These concepts help you create structured, reusable, and maintainable PHP applications.

2. Creating a Class and an Object

A class is created using the class keyword. An object is created using the new keyword.

<?php
class Student {
    public $name = "Rahul";
    public $course = "PHP";

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

$student1 = new Student();

$student1->displayInfo();
?>

Output:

Name: Rahul
Course: PHP

Here, Student is a class and $student1 is an object.

The -> operator accesses an object's properties and methods.

3. Properties and Methods

Properties store an object's data, while methods define the actions that an object can perform.

<?php
class Mobile {
    public $brand;
    public $price;

    public function showDetails(): void {
        echo "Brand: " . $this->brand . "<br>";
        echo "Price: Rs. " . $this->price;
    }
}

$mobile1 = new Mobile();

$mobile1->brand = "Samsung";
$mobile1->price = 15000;

$mobile1->showDetails();
?>

Output:

Brand: Samsung
Price: Rs. 15000

The $this keyword refers to the current object inside a non-static instance method.

Each object can have its own property values, even when multiple objects are created from the same class.

4. The Constructor Method

The __construct() method is a special PHP method that is called automatically when an object is instantiated.

<?php
class Employee {
    public string $name;
    public float $salary;

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

    public function showEmployee(): void {
        echo "Name: " . $this->name . "<br>";
        echo "Salary: Rs. " . number_format($this->salary, 2);
    }
}

$employee1 = new Employee("Amit", 25000);
$employee1->showEmployee();
?>

Output:

Name: Amit
Salary: Rs. 25,000.00

The constructor receives values when the object is created and uses them to initialize its properties.

5. Access Modifiers in PHP

Access modifiers control where class properties and methods can be accessed.

  • public — accessible wherever the object or class member is accessible.
  • protected — accessible inside the class and its subclasses.
  • private — accessible only within the class that declares the member.
<?php
class BankAccount {
    public string $owner;

    protected string $accountType = "Savings";

    private float $balance = 5000;

    public function __construct(string $owner) {
        $this->owner = $owner;
    }

    public function showBalance(): void {
        echo "Owner: " . $this->owner . "<br>";
        echo "Account Type: " . $this->accountType . "<br>";
        echo "Balance: Rs. " . number_format($this->balance, 2);
    }
}

$account = new BankAccount("Rahul");
$account->showBalance();

// This would cause an error:
// echo $account->balance;
?>

The private balance is accessed through a public method instead of being accessed directly from outside the class.

This is a basic example of encapsulation.

6. The $this Keyword

The $this keyword refers to the current object. It is commonly used to access instance properties and call instance methods.

<?php
class Product {
    public string $name;
    public float $price;

    public function setDetails(
        string $name,
        float $price
    ): void {
        $this->name = $name;
        $this->price = $price;
    }

    public function showPrice(): void {
        echo $this->name . ": Rs. " .
            number_format($this->price, 2);
    }
}

$product1 = new Product();
$product1->setDetails("Keyboard", 800);
$product1->showPrice();
?>

Output:

Keyboard: Rs. 800.00

In $this->name, the property belongs to the current object. The parameter $name is the value passed into the method.

7. Static Properties and Methods

Static properties and methods belong to the class rather than to a particular object.

Access them using the scope resolution operator ::.

<?php
class MathHelper {
    public static float $pi = 3.14159;

    public static function square(int $number): int {
        return $number * $number;
    }
}

echo "Pi: " . MathHelper::$pi . "<br>";
echo "Square: " . MathHelper::square(5);
?>

Output:

Pi: 3.14159
Square: 25

A static method can be called without creating an object. It cannot use $this because it is not operating on a particular instance.

Static members are useful for shared utilities and class-level operations.

8. Encapsulation and Getters and Setters

Encapsulation keeps data and related methods together and controls how internal values are accessed or changed.

<?php
class StudentRecord {
    private string $name;
    private int $marks;

    public function __construct(
        string $name,
        int $marks
    ) {
        $this->setName($name);
        $this->setMarks($marks);
    }

    public function setName(string $name): void {
        if (trim($name) === "") {
            throw new InvalidArgumentException(
                "Name cannot be empty."
            );
        }

        $this->name = $name;
    }

    public function setMarks(int $marks): void {
        if ($marks < 0 || $marks > 100) {
            throw new InvalidArgumentException(
                "Marks must be between 0 and 100."
            );
        }

        $this->marks = $marks;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getMarks(): int {
        return $this->marks;
    }
}

$student = new StudentRecord("Priya", 85);

echo "Name: " . $student->getName() . "<br>";
echo "Marks: " . $student->getMarks();
?>

Output:

Name: Priya
Marks: 85

Getters return property values, while setters update them after applying validation rules.

Because the properties are private, outside code cannot change them directly. It must use the methods provided by the class.

9. Practical Example: Student Management

This example combines a class, a constructor, private properties, and methods to manage a student.

<?php
class Student {
    private int $studentId;
    private string $name;
    private string $course;
    private float $fee;

    public function __construct(
        int $studentId,
        string $name,
        string $course,
        float $fee
    ) {
        if ($studentId <= 0) {
            throw new InvalidArgumentException(
                "Student ID must be positive."
            );
        }

        if (trim($name) === "" || trim($course) === "") {
            throw new InvalidArgumentException(
                "Name and course are required."
            );
        }

        if ($fee < 0) {
            throw new InvalidArgumentException(
                "Fee cannot be negative."
            );
        }

        $this->studentId = $studentId;
        $this->name = $name;
        $this->course = $course;
        $this->fee = $fee;
    }

    public function displayDetails(): void {
        echo "Student ID: " . $this->studentId . "<br>";
        echo "Name: " . $this->name . "<br>";
        echo "Course: " . $this->course . "<br>";
        echo "Total Fee: Rs. " .
            number_format($this->fee, 2);
    }
}

try {
    $student1 = new Student(
        101,
        "Rahul Kumar",
        "ADCA",
        10000
    );

    $student1->displayDetails();

} catch (InvalidArgumentException $e) {
    echo htmlspecialchars(
        $e->getMessage(),
        ENT_QUOTES | ENT_SUBSTITUTE,
        "UTF-8"
    );
}
?>

Output:

Student ID: 101
Name: Rahul Kumar
Course: ADCA
Total Fee: Rs. 10,000.00

In a real student management application, student records would typically be stored in a database. A class can represent one student and provide methods to validate or manage that student's information.


🧠 Quick Quiz

1. Which keyword is used to create a class in PHP?




2. Which keyword creates an object from a class?




3. Which access modifier restricts access to the declaring class?