Object-Oriented Programming (OOP) in PHP


Object-Oriented Programming in PHP

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into reusable, self-contained objects that contain both data (properties) and behavior (methods). PHP has supported OOP since version 4, with significantly improved implementation in PHP 5 and later versions.



Key Concepts of OOP in PHP

1. Classes and Objects

Class: A blueprint or template for creating objects

Object: An instance of a class

class Car {
    // Properties (attributes)
    public $model;
    public $color;
    
    // Methods (functions)
    public function startEngine() {
        return "Engine started!";
    }
}

// Create an object (instance of the class)
$myCar = new Car();
$myCar->model = "Toyota";
echo $myCar->startEngine();


The Four Pillars of OOP

a. Encapsulation

Bundling data and methods that operate on that data within a single unit (class). Controlling access to internal state using visibility modifiers:

  • public: Accessible from anywhere
  • protected: Accessible within the class and its child classes
  • private: Accessible only within the class
class BankAccount {
    private $balance = 0;
    
    public function deposit($amount) {
        $this->balance += $amount;
    }
    
    public function getBalance() {
        return $this->balance;
    }
}


b. Inheritance

Creating new classes (child classes) from existing ones (parent classes). Achieved using the extends keyword.

class Vehicle {
    public $wheels = 4;
}

class Motorcycle extends Vehicle {
    public $wheels = 2; // Overriding the property
}


c. Polymorphism

Objects of different classes can be treated as objects of a common superclass. Often implemented through method overriding or interfaces.

interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound() {
        return "Bark!";
    }
}

class Cat implements Animal {
    public function makeSound() {
        return "Meow!";
    }
}


d. Abstraction

Hiding complex implementation details and showing only essential features. Achieved through abstract classes and interfaces.

abstract class Shape {
    abstract public function calculateArea();
}

class Circle extends Shape {
    private $radius;
    
    public function calculateArea() {
        return pi() * $this->radius * $this->radius;
    }
}


Other OOP Features in PHP

  • Constructors and Destructors: __construct() and __destruct()
  • Static Properties and Methods: Accessed using :: (scope resolution operator)
  • Magic Methods: __get(), __set(), __toString(), etc.
  • Namespaces: Organize classes and prevent naming conflicts
  • Traits: Reuse code in multiple classes (horizontal inheritance)


Benefits of OOP in PHP

  • Code Reusability: Create reusable components
  • Modularity: Break complex problems into smaller, manageable parts
  • Maintainability: Easier to update and modify code
  • Scalability: Better structure for large applications
  • Security: Proper encapsulation protects data integrity


Complete OOP Example

<?php
// Define an interface
interface Loggable {
    public function log($message);
}

// Create an abstract class
abstract class DatabaseModel {
    protected $connection;
    
    abstract public function save();
    abstract public function delete();
}

// Implement a concrete class
class User extends DatabaseModel implements Loggable {
    private $name;
    private $email;
    
    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
        $this->connection = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
    }
    
    public function save() {
        // Save to database implementation
        return "User saved!";
    }
    
    public function delete() {
        // Delete from database implementation
        return "User deleted!";
    }
    
    public function log($message) {
        file_put_contents('log.txt', $message, FILE_APPEND);
    }
    
    public function getName() {
        return $this->name;
    }
}

// Usage
$user = new User("John Doe", "john@example.com");
echo $user->save();
$user->log("User created at " . date('Y-m-d H:i:s'));

// Demonstrate polymorphism
function showMessage(Loggable $logger, $message) {
    $logger->log($message);
}

showMessage($user, "This is a polymorphic call!");
?>