PHP OOP Introduction

PHP OOP Introduction

Object-Oriented Programming (OOP) is a paradigm that organises code into objects — bundles of data (properties) and behaviour (methods).

1 - Why OOP?

  • Encapsulation — hide internal details, expose a clean interface
  • Inheritance — reuse code from parent classes
  • Polymorphism — same interface, different implementations
  • Abstraction — model real-world concepts as objects

2 - Procedural vs OOP

// Procedural
function getArea($w, $h) { return $w * $h; }
echo getArea(5, 3); // 15

// OOP
class Rectangle {
    public function __construct(
        private float $width,
        private float $height
    ) {}

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

$rect = new Rectangle(5, 3);
echo $rect->area(); // 15

3 - A More Complete Example

class BankAccount {
    private float $balance = 0;

    public function __construct(private string $owner) {}

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

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

    public function __toString(): string {
        return "{$this->owner}: $" . number_format($this->balance, 2);
    }
}

$account = new BankAccount("Alice");
$account->deposit(1000);
$account->deposit(250.50);
echo $account; // Alice: $1,250.50

Note: PHP 8 supports constructor property promotion — you can declare and assign class properties directly in the constructor signature, cutting boilerplate significantly.

-Tip-