← Back to blog
9/20/2025

Mastering Object-Oriented Programming (OOP) in PHP

Object-Oriented Programming OOP is a paradigm shift in how we write PHP code. Unlike procedural programming, which is a series of instructions execu...

Object-Oriented Programming (OOP) is a paradigm shift in how we write PHP code. Unlike procedural programming, which is a series of instructions executed one after another, OOP organizes code into objects that represent real-world entities. This makes your applications more modular, reusable, and maintainable.


Why OOP Matters in PHP

  • Procedural PHP: Functions and code are executed in sequence, good for small scripts but messy in large projects.
  • OOP PHP: Code is modeled after real-world concepts. For example, a Car object can have startEngine() and drive() methods.

Advantages of OOP:

  1. Reusability – Write once, use in multiple places.
  2. Maintainability – Easier to manage complex applications.
  3. Encapsulation – Protect sensitive data within objects.
  4. Scalability – Add new features without breaking old ones.

1. Classes and Objects

A class is a blueprint; an object is an instance of that class.

<?php
class Car {
    public $brand;
    public $color;

    public function drive() {
        return "The $this->color $this->brand is driving.";
    }
}

$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->color = "Red";

echo $myCar->drive(); 
// Output: The Red Toyota is driving.
?>

2. Constructors and Destructors

  • Constructor (__construct) initializes properties when the object is created.
  • Destructor (__destruct) cleans up when the object is destroyed.
<?php
class User {
    public $name;

    public function __construct($name) {
        $this->name = $name;
        echo "User $name created.<br>";
    }

    public function __destruct() {
        echo "User {$this->name} destroyed.<br>";
    }
}

$user = new User("Andy");
?>

3. Access Modifiers

Access control ensures encapsulation:

  • public: Accessible from anywhere.
  • protected: Accessible only within the class and subclasses.
  • private: Accessible only within the class itself.
<?php
class BankAccount {
    private $balance = 0;

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

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

$account = new BankAccount();
$account->deposit(100);
echo $account->getBalance(); // 100
?>

4. Inheritance

Inheritance allows a class to derive properties and methods from another.

<?php
class Animal {
    public function speak() {
        return "Some sound";
    }
}

class Dog extends Animal {
    public function speak() {
        return "Bark";
    }
}

$dog = new Dog();
echo $dog->speak(); // Bark
?>

5. Polymorphism

Polymorphism means many forms. In PHP, this is done via abstract classes and interfaces.

Using Abstract Classes

<?php
abstract class Shape {
    abstract public function area();
}

class Circle extends Shape {
    private $radius;
    public function __construct($radius) {
        $this->radius = $radius;
    }
    public function area() {
        return pi() * pow($this->radius, 2);
    }
}

$circle = new Circle(5);
echo $circle->area(); // 78.53
?>

Using Interfaces

<?php
interface PaymentGateway {
    public function pay($amount);
}

class PayPal implements PaymentGateway {
    public function pay($amount) {
        return "Paid $amount using PayPal";
    }
}

$paypal = new PayPal();
echo $paypal->pay(100);
?>

6. Static Properties and Methods

Static members belong to the class, not an object.

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

    public static function square($n) {
        return $n * $n;
    }
}

echo MathHelper::$pi; // 3.14
echo MathHelper::square(4); // 16
?>

7. Namespaces and Autoloading

As projects grow, namespaces prevent name conflicts.

<?php
namespace App\Models;

class User {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}
?>

When combined with Composer autoloading, namespaces make large projects manageable.


8. Traits (Code Reuse Without Inheritance)

Traits let you reuse code across multiple classes.

<?php
trait Logger {
    public function log($msg) {
        echo "[LOG]: $msg<br>";
    }
}

class FileManager {
    use Logger;
}

$fileManager = new FileManager();
$fileManager->log("File uploaded");
?>

9. Practical Example – Library Management System

<?php
class Book {
    private $title;
    private $author;

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

    public function getDetails() {
        return "{$this->title} by {$this->author}";
    }
}

class User {
    private $name;
    private $borrowedBooks = [];

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

    public function borrowBook(Book $book) {
        $this->borrowedBooks[] = $book;
    }

    public function listBorrowedBooks() {
        foreach ($this->borrowedBooks as $book) {
            echo $book->getDetails() . "<br>";
        }
    }
}

class Library {
    private $books = [];

    public function addBook(Book $book) {
        $this->books[] = $book;
    }

    public function showBooks() {
        foreach ($this->books as $book) {
            echo $book->getDetails() . "<br>";
        }
    }
}

// Usage
$library = new Library();
$book1 = new Book("1984", "George Orwell");
$book2 = new Book("Clean Code", "Robert C. Martin");

$library->addBook($book1);
$library->addBook($book2);

$user = new User("Andy");
$user->borrowBook($book1);

echo "<h3>Library Collection:</h3>";
$library->showBooks();

echo "<h3>Borrowed Books:</h3>";
$user->listBorrowedBooks();
?>

Conclusion

OOP in PHP is not just about syntax—it’s a way of thinking. By modeling real-world entities into classes and objects, using inheritance, encapsulation, and polymorphism, you can build scalable and professional applications.

With this knowledge, you can now explore design patterns (like Singleton, Factory, MVC) and apply them in frameworks such as Laravel and Symfony.