Discover the foundational principles of Object-Oriented Programming (OOP) in PHP. This comprehensive guide covers everything from classes and objects to inheritance, polymorphism, and practical use-cases that will elevate your PHP applications.
PHP has evolved over the years from a simple scripting language to one that supports full-fledged object-oriented programming (OOP) features. Embracing OOP principles can lead to more organized, maintainable, and reusable code. In this guide, we’ll walk through the core concepts of OOP in PHP with detailed examples so you can see how each step works.
Table of Contents
- What is OOP?
- Setting Up Your Environment
- Classes and Objects
- Properties and Methods
- Constructors
- Encapsulation with Access Modifiers
- Inheritance
- Polymorphism
- Practical Example: Building a Simple User System
- Conclusion
1. What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects rather than functions and logic alone. It focuses on four core concepts:
- Encapsulation – Bundling data and methods within a class.
- Inheritance – Reusing properties and methods of existing classes in new classes.
- Polymorphism – Allowing objects of different types to respond differently to the same method call.
- Abstraction – Hiding complex implementation details while exposing a simplified interface.
With OOP in PHP, you can write cleaner and more efficient code, reduce redundancy, and create applications that are easier to maintain and scale.
2. Setting Up Your Environment
Before we dive into the examples, make sure you have a working environment:
- Web Server – Such as Apache or Nginx.
- PHP Installed – PHP 7.4 or above is recommended for modern OOP features like typed properties and arrow functions.
- Text Editor or IDE – Use any code editor (VS Code, PhpStorm, Sublime Text, etc.) where you can organize your project’s files.
Once your environment is set up, create a new folder (e.g., php-oop-guide/
) and a file named index.php
where we’ll place our code.
3. Classes and Objects
A class in PHP is like a blueprint that defines properties (variables) and methods (functions). An object is an instance of that class.
Example
<?php
// Define a class
class Car {
// This is currently an empty class
}
// Create an object (instance) of Car
$toyota = new Car();
// Verify the object
var_dump($toyota);
?>
Explanation
Car
is the class.$toyota
is an object/instance ofCar
.new Car()
creates a new object based on theCar
class blueprint.
4. Properties and Methods
Properties are variables within a class, and methods are functions that belong to a class.
Example
<?php
class Car {
// Properties
public $brand;
public $color;
// Method
public function drive() {
return "The $this->brand is driving.";
}
}
// Create an instance of Car
$toyota = new Car();
// Assign properties
$toyota->brand = "Toyota";
$toyota->color = "Red";
// Call the method
echo $toyota->drive(); // Outputs: "The Toyota is driving."
?>
Explanation
public $brand
andpublic $color
are properties.- The method
drive()
references$this->brand
to get the value of thebrand
property from the current instance. - After creating the
$toyota
object, we set its properties and invoke thedrive()
method.
5. Constructors
A constructor is a special method that gets automatically called when an object is created. It’s commonly used to initialize properties or run setup routines.
Example
<?php
class Car {
public $brand;
public $color;
// Constructor
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
public function drive() {
return "The $this->color $this->brand is driving.";
}
}
// Create an instance of Car with constructor arguments
$toyota = new Car("Toyota", "Red");
echo $toyota->drive(); // Outputs: "The Red Toyota is driving."
?>
Explanation
- The
__construct()
method takes$brand
and$color
as parameters. - Immediately upon object creation, PHP calls
__construct()
, and the object’sbrand
andcolor
properties are set.
6. Encapsulation with Access Modifiers
Encapsulation is about restricting direct access to some of an object’s components. This is often implemented via access modifiers:
- public – Accessible everywhere.
- protected – Accessible only within the class and classes deriving from it.
- private – Accessible only within the class itself.
Example
<?php
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
// Public method to get balance
public function getBalance() {
return $this->balance;
}
// Public method to deposit funds
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
}
$account = new BankAccount(1000);
$account->deposit(500);
echo $account->getBalance(); // Outputs: 1500
?>
Explanation
$balance
is markedprivate
. It cannot be accessed directly outside the class.- Instead, we use
getBalance()
to retrieve it anddeposit()
to modify it. - This approach prevents external code from arbitrarily tampering with
$balance
.
7. Inheritance
Inheritance allows a class to inherit properties and methods from another class. The class that inherits is called the child (or subclass), and the class being inherited from is the parent (or superclass).
Example
<?php
// Parent class
class Vehicle {
protected $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function startEngine() {
return "{$this->brand} engine started!";
}
}
// Child class
class Car extends Vehicle {
public function drive() {
return "The {$this->brand} is now driving.";
}
}
$myCar = new Car("Honda");
echo $myCar->startEngine(); // Output: "Honda engine started!"
echo $myCar->drive(); // Output: "The Honda is now driving."
?>
Explanation
class Vehicle
is the parent class with a$brand
property and astartEngine()
method.class Car extends Vehicle
inherits the parent’s properties and methods. We add a newdrive()
method toCar
.- When creating a new
Car
, the constructor ofVehicle
is automatically called (because ofextends
), setting$brand
.
8. Polymorphism
Polymorphism allows child classes to have different implementations of methods that share the same name in the parent class. This is usually done using method overriding.
Example
<?php
class Animal {
public function makeSound() {
return "Some generic animal sound";
}
}
class Dog extends Animal {
// Method overriding
public function makeSound() {
return "Bark!";
}
}
class Cat extends Animal {
// Method overriding
public function makeSound() {
return "Meow!";
}
}
function animalSound(Animal $animal) {
echo $animal->makeSound() . PHP_EOL;
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // Bark!
animalSound($cat); // Meow!
?>
Explanation
Animal
is a parent class with a defaultmakeSound()
method.Dog
andCat
overridemakeSound()
to provide their own implementations.animalSound()
accepts anAnimal
type, yet it correctly outputs different sounds depending on which subclass is passed.
9. Practical Example: Building a Simple User System
Let’s build a very simplified user system to see how these concepts tie together.
Step-by-Step
-
Create a Base Class (
User
)<?php class User { protected $username; protected $email; public function __construct($username, $email) { $this->username = $username; $this->email = $email; } public function getUsername() { return $this->username; } public function getEmail() { return $this->email; } } ?>
User
class hasprotected
properties$username
and$email
.- The constructor initializes these properties.
-
Extend the Base Class for a Specific User Type (
Admin
)<?php class Admin extends User { private $adminLevel; public function __construct($username, $email, $adminLevel) { // Call parent constructor to set username and email parent::__construct($username, $email); $this->adminLevel = $adminLevel; } public function getAdminLevel() { return $this->adminLevel; } // Polymorphism: Overriding a method (or adding a new one if needed) public function getDetails() { return "Admin: {$this->username}, Level: {$this->adminLevel}, Email: {$this->email}"; } } ?>
Admin
extendsUser
, so it inheritsusername
andemail
.parent::__construct()
calls theUser
constructor to initialize inherited properties.- An additional property
$adminLevel
is introduced.
-
Create Objects and Use Methods
<?php // Include or require the class files // require_once 'User.php'; // require_once 'Admin.php'; // Create a regular user $user = new User("john_doe", "[email protected]"); echo $user->getUsername(); // Output: john_doe echo $user->getEmail(); // Output: [email protected] // Create an admin user $admin = new Admin("admin_01", "[email protected]", 5); echo $admin->getAdminLevel(); // Output: 5 echo $admin->getDetails(); // Output: "Admin: admin_01, Level: 5, Email: [email protected]" ?>
- Demonstrates how to create instances of both
User
andAdmin
and interact with their properties and methods.
- Demonstrates how to create instances of both
With this user system, you can build upon it to add more functionality, such as authentication, role-based permissions, and more advanced user management features.
10. Conclusion
Object-Oriented Programming in PHP empowers you to write cleaner, more modular code. By encapsulating properties, using inheritance effectively, and leveraging polymorphism, you can build applications that are flexible and easier to maintain over time.
Key Takeaways
- Classes & Objects organize your code into logical blueprints and their instances.
- Constructors handle initialization when objects are created.
- Access Modifiers enforce encapsulation and protect sensitive data.
- Inheritance & Polymorphism reduce code duplication and promote extensibility.
With a solid understanding of these fundamentals, you’re well on your way to mastering PHP OOP. Happy coding!
Additional Resources
- PHP Manual – Classes and Objects
- PSR Standards for coding style and best practices
If you found this guide helpful, feel free to share it with fellow developers looking to level up their PHP skills.