The four main principles of Object-Oriented Programming (OOP) are Encapsulation, Inheritance, Polymorphism, and Abstraction. Here’s a breakdown of each principle along with examples of how they can be applied in PHP:
1. Encapsulation
Encapsulation is the concept of restricting direct access to certain details of an object and only exposing what is necessary. This is achieved using access modifiers like private
, protected
, and public
.
Example in PHP
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount(1000);
$account->deposit(500);
echo $account->getBalance(); // Outputs: 1500
- Here,
$balance
isprivate
, preventing direct modification. - Methods
deposit()
andgetBalance()
act as controlled access points.
2. Inheritance
Inheritance allows a class to inherit properties and methods from another class, promoting code reusability.
Example in PHP
class Vehicle {
protected $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function getBrand() {
return $this->brand;
}
}
class Car extends Vehicle {
private $model;
public function __construct($brand, $model) {
parent::__construct($brand);
$this->model = $model;
}
public function getCarInfo() {
return "Brand: " . $this->getBrand() . ", Model: " . $this->model;
}
}
$car = new Car("Toyota", "Corolla");
echo $car->getCarInfo(); // Outputs: Brand: Toyota, Model: Corolla
Car
inherits from Vehicle
, reusing its methods and properties.
3. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common base class. This is typically achieved using method overriding or interfaces.
Example in PHP
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
return "Bark";
}
}
class Cat implements Animal {
public function makeSound() {
return "Meow";
}
}
function animalSound(Animal $animal) {
echo $animal->makeSound();
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // Outputs: Bark
animalSound($cat); // Outputs: Meow
The makeSound()
method is implemented differently in Dog
and Cat
, but they are treated as Animal
objects.
4. Abstraction
Abstraction hides implementation details and only exposes essential functionalities.
Example in PHP
abstract class Payment {
abstract public function processPayment($amount);
}
class CreditCardPayment extends Payment {
public function processPayment($amount) {
return "Processing Credit Card payment of $" . $amount;
}
}
class PayPalPayment extends Payment {
public function processPayment($amount) {
return "Processing PayPal payment of $" . $amount;
}
}
$payment = new CreditCardPayment();
echo $payment->processPayment(100); // Outputs: Processing Credit Card payment of $100
The Payment
class defines an abstract method processPayment()
, which is implemented differently by CreditCardPayment
and PayPalPayment
.
Summary
OOP Principle | Description | Example |
---|---|---|
Encapsulation | Restricting direct access to object properties | Private $balance in BankAccount |
Inheritance | Reusing properties/methods of a parent class | Car extends Vehicle |
Polymorphism | Same interface, different implementations | Dog and Cat implement Animal |
Abstraction | Hiding implementation details | Payment class with processPayment() |
How Inheritance Works in PHP
Inheritance in PHP allows one class (child class) to inherit properties and methods from another class (parent class). This promotes code reusability and maintainability.
Basic Example in PHP
- The
ChildClass
inheritsgreet()
fromParentClass
, avoiding redundant code. - The
parent::__construct()
function ensures that the parent’s constructor logic is also executed.
How I’ve Used Inheritance in Drupal Modules
In Drupal module development, inheritance is commonly used when:
- Extending core classes.
- Creating custom plugin classes.
- Implementing reusable functionality in service classes.
Example 1: Extending a Core Drupal Controller
When creating a custom controller, extending ControllerBase
provides access to Drupal services.
CustomController
inherits helper methods like$this->t()
fromControllerBase
.
Example 2: Extending a Form Class
When creating custom forms, extending FormBase
or ConfigFormBase
ensures compliance with Drupal's Form API.
CustomForm
extendsFormBase
, inheritingbuildForm()
,validateForm()
, andsubmitForm()
.
Example 3: Extending a Plugin Class
When defining custom block plugins, extending BlockBase
ensures adherence to Drupal’s block system.
CustomBlock
extendsBlockBase
, inheriting essential block functionalities.
Key Takeaways
Use Case | Parent Class | Child Class |
---|---|---|
Custom Controller | ControllerBase | CustomController |
Custom Form | FormBase | CustomForm |
Custom Block | BlockBase | CustomBlock |
Implementing Interfaces and Abstract Classes in PHP
Both interfaces and abstract classes in PHP define a structure for classes but differ in key ways. Below, I'll explain their differences, how to implement them, and when to use each.
1. Abstract Classes
An abstract class can have both abstract (unimplemented) methods and regular (implemented) methods. It cannot be instantiated directly and must be extended by child classes.
Example in PHP
Key Features of Abstract Classes
✅ Can have both abstract and concrete methods.
✅ Can define properties (like $amount
).
✅ Supports constructor inheritance.
✅ Used when multiple related classes share common behavior.
2. Interfaces
An interface defines only method signatures, and any class that implements the interface must provide implementations for all the methods.
Example in PHP
Key Features of Interfaces
✅ Only method declarations (no properties or concrete methods).
✅ A class can implement multiple interfaces (PHP does not support multiple inheritance).
✅ Used to enforce consistent behavior across multiple unrelated classes.
When to Choose Abstract Classes vs. Interfaces
Feature | Abstract Class | Interface |
---|---|---|
Can have concrete methods? | ✅ Yes | ❌ No |
Can have properties? | ✅ Yes | ❌ No |
Supports multiple inheritance? | ❌ No | ✅ Yes (via multiple interfaces) |
When to use? | When classes share common behavior and properties | When unrelated classes need to follow the same structure |
Usage in Drupal Modules
Example 1: Using an Abstract Class in a Drupal Service
In Drupal services, abstract classes help define reusable logic.
- Here,
LoggerService
provides a common structure for loggers. FileLogger
implements thelog()
method.
Example 2: Using an Interface for a Custom Drupal Plugin
Interfaces are commonly used in Drupal plugins to ensure a common structure.
- Different processors (CSV, JSON) implement the same interface but behave differently.
- This ensures consistency and flexibility across processors.
Final Thoughts
✅ Use Abstract Classes when different classes share common properties and behavior.
✅ Use Interfaces when different classes must follow the same structure but may not be related.