
Mastering OOP in PHP - Complete Object-Oriented Programming Guide (2025)
Object-Oriented Programming (OOP) has revolutionized the way we build scalable, maintainable applications in PHP. While early PHP was procedural, modern PHP (especially post PHP 5+) fully embraces OOP - enabling you to write modular, clean, and reusable code.
This guide walks you through everything about PHP OOP, from scratch to advanced usage, including real-world examples, best practices, and modern architecture patterns used in frameworks like Laravel, Symfony, and Magento.
1. What is OOP?
OOP (Object-Oriented Programming) is a programming paradigm based on the concept of "objects" - which contain properties (data) and methods (behavior).
OOP helps you:
- Organize code better
- Reuse functionality
- Improve maintainability
- Follow modern software architecture patterns
2. Classes and Objects
A class is a blueprint for creating objects.
class Car {
public $brand;
public function drive() {
echo "Driving the car";
}
}
// Creating an object
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->drive(); // Output: Driving the car
3. Properties and Methods
- Properties are variables inside a class.
- Methods are functions inside a class.
class User {
public $name;
public function greet() {
echo "Hello, $this->name";
}
}
Use $this->
to refer to the current object’s properties or methods.
4. Constructors and Destructors
Constructor: Automatically runs when an object is created.
class Product {
public $title;
public function __construct($title) {
$this->title = $title;
}
}
Destructor: Called when the object is destroyed.
public function __destruct() {
echo "Cleaning up " . $this->title;
}
5. Access Modifiers
Control access to properties/methods.
Modifier | Meaning |
---|---|
public |
Accessible from anywhere |
private |
Accessible only within the class |
protected |
Accessible within class and subclasses |
Example:
class Account {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
}
6. Inheritance
Inheritance allows a class to extend another.
class Animal {
public function speak() {
echo "Some sound";
}
}
class Dog extends Animal {
public function speak() {
echo "Bark!";
}
}
$d = new Dog();
$d->speak(); // Bark!
7. Static Methods and Properties
Static members belong to the class, not the object.
class Math {
public static $pi = 3.14;
public static function square($x) {
return $x * $x;
}
}
echo Math::$pi;
echo Math::square(5);
8. Encapsulation
Encapsulation hides internal class details and exposes only necessary parts.
Use private
/protected
with getter/setter methods:
class BankAccount {
private $balance = 0;
public function getBalance() {
return $this->balance;
}
public function deposit($amount) {
if ($amount > 0) $this->balance += $amount;
}
}
9. Polymorphism
Polymorphism allows different classes to use the same interface with different behaviors.
class Bird {
public function makeSound() {
echo "Tweet";
}
}
class Cat {
public function makeSound() {
echo "Meow";
}
}
function speak($animal) {
$animal->makeSound();
}
10. Abstraction and Interfaces
Abstract Class
abstract class Shape {
abstract public function area();
}
class Square extends Shape {
public function area() {
return 25;
}
}
Interface
interface Logger {
public function log($msg);
}
class FileLogger implements Logger {
public function log($msg) {
echo "Logging to file: $msg";
}
}
11. Traits (Code Reuse Across Classes)
trait LoggerTrait {
public function log($msg) {
echo "Log: $msg";
}
}
class App {
use LoggerTrait;
}
12. Namespaces and Autoloading
Namespace
namespace App\Models;
class User {}
Autoloading via Composer
In composer.json
:
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
Run:
composer dump-autoload
13. Magic Methods in PHP
Method | Purpose |
---|---|
__construct() |
Called when object is created |
__destruct() |
Called when object is destroyed |
__get() |
Accessing inaccessible property |
__set() |
Writing to inaccessible property |
__call() |
Call to undefined method |
__toString() |
Object to string conversion |
14. Dependency Injection (DI)
DI allows objects to be passed into classes rather than hardcoding them.
class EmailService {
public function send($msg) {
echo "Sending: $msg";
}
}
class UserController {
protected $email;
public function __construct(EmailService $email) {
$this->email = $email;
}
public function notify() {
$this->email->send("Welcome!");
}
}
15. SOLID Principles
Principle | Description |
---|---|
S – Single Responsibility | Each class does one thing only |
O – Open/Closed | Open for extension, closed for modification |
L – Liskov Substitution | Subclasses should be substitutable |
I – Interface Segregation | Small, client-specific interfaces |
D – Dependency Inversion | High-level code shouldn’t depend on low-level code |
16. Common Design Patterns in PHP
- Singleton – Ensure only one instance of a class
- Factory – Create objects without specifying exact class
- Strategy – Define a family of algorithms
- Repository – Encapsulate DB logic
- Service Container – Manage class dependencies
17. Real-World Use Cases of OOP in PHP
- Model–View–Controller (MVC) apps
- Laravel services and facades
- Symfony components
- Magento eCommerce logic
- Reusable libraries/packages
- Authentication and middleware
18. Best Practices for OOP in PHP
- Keep class responsibility focused
- Use interfaces and dependency injection
- Favor composition over inheritance
- Use PSR standards (PSR-4 autoloading, PSR-12 coding style)
- Write unit tests for class behavior
- Follow SOLID design principles
Final Thoughts
OOP in PHP opens up a world of modularity, power, and scalability. Whether you're writing basic classes or designing enterprise apps with advanced design patterns - understanding and using OOP effectively is key to becoming a skilled PHP developer.
The more you embrace OOP, the cleaner and more future-proof your code becomes.