Lesson 47 of 50 – PHP Classes and Objects
94%

PHP Classes and Objects

Classes and objects are the foundation of Object-Oriented Programming (OOP) in PHP. A class defines properties and methods, while an object is an instance created from that class.

In this lesson, you will learn how to create classes and objects, define properties and methods, use constructors, create multiple objects, and work with object methods in practical examples.

1. What Is a Class?

A class is a blueprint that defines the properties and methods that its objects can have.

Example:

<?php
class Student {
    public $name;
    public $course;
}
?>

In this example, Student is a class with two public properties: $name and $course.

The class defines the structure, but no student object has been created yet.

Remember:

  • Use the class keyword to declare a class.
  • Class names conventionally begin with an uppercase letter.
  • Properties store data associated with objects.
  • Methods define behavior associated with objects.
2. What Is an Object?

An object is an instance of a class. You can create an object using the new keyword.

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

$student1 = new Student();

echo $student1->name . "<br>";
echo $student1->course;
?>

Output:

Rahul
PHP

Here, $student1 refers to an object created from the Student class.

The -> operator is used to access an object's properties and methods.

3. Creating Multiple Objects

You can create multiple objects from the same class. Each object can store its own property values.

<?php
class Student {
    public $name;
    public $course;
}

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

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

echo $student1->name . " - " . $student1->course . "<br>";
echo $student2->name . " - " . $student2->course;
?>

Output:

Rahul - ADCA
Priya - Web Development

Both objects use the same class definition, but their property values are independent.

This approach is useful when managing many students, employees, products, or library members.

4. Defining Methods in a Class

A method is a function declared inside a class. It describes an action that an object can perform.

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

    public function multiply(int $a, int $b): int {
        return $a * $b;
    }
}

$calculator = new Calculator();

echo "Addition: " . $calculator->add(10, 5) . "<br>";
echo "Multiplication: " . $calculator->multiply(10, 5);
?>

Output:

Addition: 15
Multiplication: 50

The methods add() and multiply() perform calculations and return their results.

You can call a public instance method using an object followed by the -> operator.

5. Using the Constructor

The __construct() method runs automatically when a new object is created. It is commonly used to initialize object properties.

<?php
class Employee {
    public string $name;
    public string $department;

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

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

$employee1 = new Employee("Amit", "IT");
$employee1->showDetails();
?>

Output:

Name: Amit
Department: IT

The constructor receives the employee's name and department when the object is created.

The $this keyword refers to the current object, allowing its properties to be initialized.

6. Updating Object Properties

If a property is accessible, you can change its value after creating an object.

<?php
class Product {
    public string $name = "Keyboard";
    public float $price = 800;
}

$product1 = new Product();

echo "Original Price: Rs. " . $product1->price . "<br>";

$product1->price = 1000;

echo "Updated Price: Rs. " . $product1->price;
?>

Output:

Original Price: Rs. 800
Updated Price: Rs. 1000

The price changes only for the specified object. If another object is created from the same class, it has its own instance property value.

In larger applications, private properties and validated setter methods are often preferable for important data.

7. Returning Values from Object Methods

A method can calculate a value and return it using the return statement.

<?php
class Rectangle {
    public float $length;
    public float $width;

    public function __construct(
        float $length,
        float $width
    ) {
        $this->length = $length;
        $this->width = $width;
    }

    public function getArea(): float {
        return $this->length * $this->width;
    }

    public function getPerimeter(): float {
        return 2 * ($this->length + $this->width);
    }
}

$rectangle1 = new Rectangle(10, 5);

echo "Area: " . $rectangle1->getArea() . "<br>";
echo "Perimeter: " . $rectangle1->getPerimeter();
?>

Output:

Area: 50
Perimeter: 30

The getArea() method returns the area, while getPerimeter() returns the perimeter.

Returning values makes methods reusable because the results can be stored, displayed, or used in further calculations.

8. The $this Keyword in Detail

The $this keyword allows an instance method to access the current object's properties and other instance methods.

<?php
class BankAccount {
    public string $owner;
    public float $balance;

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

    public function deposit(float $amount): void {
        if ($amount > 0) {
            $this->balance += $amount;
        }
    }

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

$account1 = new BankAccount("Rahul", 5000);
$account1->deposit(1500);
$account1->showBalance();
?>

Output:

Owner: Rahul
Balance: Rs. 6,500.00

The deposit() method uses $this->balance to update the current object's balance.

This is a simple learning example. A real financial application needs stronger validation, controlled access to balances, and reliable transaction handling.

9. Practical Example: Library Book Objects

In a library management system, each book can be represented by an object with its own title, author, and availability status.

<?php
class Book {
    public string $title;
    public string $author;
    private bool $available = true;

    public function __construct(
        string $title,
        string $author
    ) {
        $this->title = $title;
        $this->author = $author;
    }

    public function issueBook(): void {
        if (!$this->available) {
            echo "Book is already issued.<br>";
            return;
        }

        $this->available = false;
        echo "Book issued successfully.<br>";
    }

    public function returnBook(): void {
        if ($this->available) {
            echo "Book is already available.<br>";
            return;
        }

        $this->available = true;
        echo "Book returned successfully.<br>";
    }

    public function showDetails(): void {
        echo "Title: " . $this->title . "<br>";
        echo "Author: " . $this->author . "<br>";
        echo "Status: " .
            ($this->available ? "Available" : "Issued") .
            "<br>";
    }
}

$book1 = new Book(
    "Learn PHP",
    "Amit Kumar"
);

$book1->showDetails();
$book1->issueBook();
$book1->showDetails();
$book1->returnBook();
$book1->showDetails();
?>

Output:

Title: Learn PHP
Author: Amit Kumar
Status: Available
Book issued successfully.
Title: Learn PHP
Author: Amit Kumar
Status: Issued
Book returned successfully.
Title: Learn PHP
Author: Amit Kumar
Status: Available

This example demonstrates how an object stores its own state and changes it through methods.

In a real library system, availability would usually be stored in a database so that multiple users and application requests can share the same information.


🧠 Quick Quiz

1. Which keyword creates an object from a class?




2. Which method is automatically called when an object is created?




3. Which operator accesses an object's properties and methods?