agyanadda@gmail.com

PHP OOP Classes and Objects

OOP and Advanced PHP 1 min read Updated Dec 1, 2026 Topic 31 of 36

Object-Oriented Programming (OOP) groups data and the functions that work on it into classes. Laravel and every modern PHP framework are built with OOP.

  • A class is a blueprint (e.g. Student)
  • An object is one thing made from it ($asha = new Student(...))

Class example

class Student
{
    public function __construct(
        public string $name,
        private int $marks = 0,
    ) {}

    public function result(): string
    {
        return $this->marks >= 33 ? 'Pass' : 'Fail';
    }
}
  • __construct() runs when you write new Student(...)
  • Constructor property promotion (PHP 8) declares and sets properties in one line
  • $this means "this object"; use -> to access properties and methods

Visibility

Keyword Accessible from
public anywhere
protected the class and its children
private only the class itself

Keep data private and expose methods — this is encapsulation.

Static and constants

public const PASS_MARK = 33; → Student::PASS_MARK. Static methods belong to the class: Student::create(...).

readonly (PHP 8.1)

public readonly string $roll; can be set once and never changed.

Example

Example — Bank account class PHP
<?php
class BankAccount
{
    public const MIN_BALANCE = 500;
    private static int $count = 0;

    public function __construct(
        public readonly string $holder,
        private float $balance = 0,
    ) {
        self::$count++;
    }

    public function deposit(float $amount): static
    {
        $this->balance += $amount;
        return $this;
    }

    public function withdraw(float $amount): static
    {
        if ($this->balance - $amount < self::MIN_BALANCE) {
            throw new Exception('Minimum balance of ₹' . self::MIN_BALANCE . ' required.');
        }
        $this->balance -= $amount;
        return $this;
    }

    public function balance(): string
    {
        return '₹' . number_format($this->balance, 2);
    }

    public static function total(): int
    {
        return self::$count;
    }
}

$asha = new BankAccount('Asha', 1000);
$asha->deposit(2500)->withdraw(800);
echo "{$asha->holder}: {$asha->balance()}<br>";

$ravi = new BankAccount('Ravi');
try {
    $ravi->withdraw(100);
} catch (Exception $e) {
    echo 'Ravi: ' . $e->getMessage() . '<br>';
}
echo 'Accounts opened: ' . BankAccount::total();

Output: Asha: ₹2,700.00 / Ravi: Minimum balance of ₹500 required. / Accounts opened: 2

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which keyword creates an object from a class?

Exercise 2 True / False

A private property can be read from outside the class.

Exercise 3 Fill in the Blank

Inside a method, $___ refers to the current object.

Frequently Asked Questions

As soon as your project has more than a few pages. It keeps code organised, and you need it to understand Laravel models, controllers and services.