Object-oriented programming (OOP) in PHP enables you to write more modular, maintainable, and scalable code. Let’s explore the core principles and some useful patterns.
The Four Pillars of OOP
1. Encapsulation
Bundling data and methods that operate on that data within one unit (class):
class User {
private $name;
public function setName($name) {
$this->name = trim($name);
}
public function getName() {
return $this->name;
}
}
2. Inheritance
Creating new classes from existing ones:
class Admin extends User {
// Additional admin-specific methods
}
3. Polymorphism
Objects of different classes can be used interchangeably:
interface Logger {
public function log($message);
}
class FileLogger implements Logger { /* ... */ }
class DatabaseLogger implements Logger { /* ... */ }
4. Abstraction
Hiding complex implementation details:
abstract class PaymentGateway {
abstract public function process($amount);
public function refund($amount) {
// Common refund logic
}
}
Common Design Patterns
Singleton Pattern
Ensure a class has only one instance:
class Database {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
Factory Pattern
Create objects without specifying the exact class:
class LoggerFactory {
public static function create($type) {
return match($type) {
'file' => new FileLogger(),
'db' => new DatabaseLogger(),
default => throw new InvalidArgumentException()
};
}
}
Mastering these OOP concepts will elevate your PHP development skills significantly.
