Object-Oriented Programming (OOP) – Core Concepts
August 9, 2025Object-Oriented Programming (OOP) is a modern software development approach that divides an application into units called Objects that interact with each other. This approach relies on designing code using templates called Classes, which act as blueprints for creating multiple objects that share the same properties and behaviors. OOP principles have become essential for developing large-scale projects, and most popular PHP frameworks – such as Laravel – heavily rely on OOP to provide a structured and scalable architecture.
1- Classes
Definition: A Class in OOP is essentially a model or blueprint for a logical unit that contains a set of related properties (data) and methods (behaviors). You can think of a Class as a mold used to create multiple objects with the same structure. For example, you could have a Class representing a “Car,” which defines its properties (like color and capacity) and methods that represent its actions (like moving or honking).
Importance: Classes help organize code by grouping related data and functionality in one place. Instead of writing an entire program in a single file procedurally, you can divide it into Classes, each representing a logical part of the application. This makes the code much easier to understand and maintain, especially as the project grows. Using Classes also makes code reusable; you can create multiple objects from the same Class instead of rewriting the same logic each time.
Class Components: A Class typically contains two main elements:
- Properties: Variables that represent the state or attributes of an Object. They are defined inside the Class and can have default values.
- Methods: Functions that define the behavior of an Object or what it can do. They are also defined inside the Class and can access its properties.
In PHP, you define a Class using the reserved keyword class
followed by the Class name, and within curly braces { }
you define its properties and methods. Here’s a simple example of a Class named Car
with a property $color
and a method showColor()
:
<?php
// Simple Class example
class Car {
// Property
public $color = "red";
// Method
public function showColor() {
echo "The car color is " . $this->color;
}
}
?>
In this example, we created a Class named Car
with a property $color
set to public
(meaning it’s accessible outside the Class) with a default value of "red". The Class also has a method showColor()
that prints the current car color. Notice the use of $this
inside the method – it refers to the properties of the current Object. For example, $this->color
means we’re accessing the $color
property of that specific Object instance.
2- Objects
Definition: An Object is an instance created from a specific Class during program execution. If a Class is the blueprint, then an Object is the final product made from it. Each Object holds its own data (property values) and can use the methods defined in the Class. In real-world terms, an Object represents a specific thing or component in the application. Objects are the fundamental building blocks that run the program in OOP.
Importance: Objects allow us to create multiple independent instances from the same Class, each with its own unique state. This is extremely useful for managing varying data without duplicating code. For example, we can create several Car
Objects, each with a different color. Each Object stores its own color value, while all share the same methods from the Class.
Object Characteristics: Each Object has:
- State: The values of its properties at a specific moment (e.g., the current color of the car).
- Behavior: The ability to perform actions (methods) defined in its Class using its own data.
- Identity: Each Object is unique, even if it’s from the same Class and has identical data.
To create a new Object in PHP, we use the new
keyword followed by the Class name. We then access its properties and methods using the ->
operator. Here’s an example of creating two Car
Objects and modifying their properties:
<?php
// Creating objects from the Car Class
$car1 = new Car();
$car2 = new Car();
// Changing the color property for each object
$car1->color = "blue";
$car2->color = "green";
// Using method to display the color
$car1->showColor(); // The car color is blue
$car2->showColor(); // The car color is green
?>
Here, we created two Objects, $car1
and $car2
, from the Car
Class using new
. Each Object has its own $color
property: $car1
was set to "blue" and $car2
to "green". When calling showColor()
on each Object, it prints the color specific to that Object. This shows we can create an unlimited number of Objects from the same Class, each holding its own data but sharing the Class’s structure.
3- Encapsulation
Definition: Encapsulation is the principle of hiding the internal implementation details of a Class and protecting its data from direct or uncontrolled access from outside the Class. Instead, the Class provides a public interface (public methods) to interact with the data in a safe way. This allows the Class developer to ensure that the code is not misused or used in an unexpected manner by other parts of the program. In practice, Encapsulation means that an Object’s internal data can only be accessed through specific methods, not directly.
Importance: This principle helps maintain the integrity of an Object’s state and prevents harmful side effects. By hiding internal data and making it private
, no external code can change it except through a defined public interface (methods). This gives better control over how the Object’s internal state is modified and reduces errors by preventing improper usage of its properties. Encapsulation also makes the code easier to maintain; if we decide to change how the data is stored or how certain behavior works, we can do it inside the Class without breaking other parts of the program, as long as the external interface (public methods) stays the same.
How to achieve Encapsulation in PHP: PHP provides three access levels for Class members, defined using access modifiers when declaring properties or methods:
private
: The property or method is restricted to the Class itself. (It cannot be accessed from outside the Class at all.)protected
: The property or method can be accessed within the Class and by Classes that inherit from it, but not from outside.public
: The property or method is accessible to everyone; it can be used anywhere in the program (inside or outside the Class).
Typically, we make properties private
to enforce Encapsulation, and provide public
methods to read or modify those properties when necessary (commonly called getters and setters). The following example shows a BankAccount
Class with a private property $balance
and public methods to deposit and withdraw funds, as well as to check the balance:
<?php
class BankAccount {
private $balance;
// Constructor to set initial balance
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
// Deposit money into the account
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
// Withdraw money from the account
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
}
}
// Get the current balance
public function getBalance() {
return $this->balance;
}
}
// Example usage
$account = new BankAccount(100);
$account->deposit(50);
$account->withdraw(30);
echo "Balance: " . $account->getBalance(); // Balance: 120
?>
In this code, the $balance
property is declared as private
, so it cannot be modified directly from outside the BankAccount
Class. We provided a deposit()
method to add money to the balance and a withdraw()
method to remove money, both validating the amount before changing the balance. There is also a getBalance()
method to return the current balance. This way, the $balance
value can only be changed through the defined methods, enforcing the Encapsulation principle and preventing incorrect changes or invalid states (like withdrawing more than the available balance).
4- Inheritance
Definition: Inheritance is a mechanism that allows you to create a new Class based on an existing Class. The new Class is called the subclass or child, while the original Class is called the base class or parent. The subclass inherits all properties and methods of the parent Class as they are, with the option to add new properties and methods or override existing methods if needed. In PHP, inheritance is implemented using the extends
keyword between the subclass name and the parent class name. The concept of inheritance helps us reuse and organize code logically; we place common features shared by multiple classes into a single base Class, and then create subclasses that share those features but add their own specific behavior. This way, we avoid repeating code in every Class.
Importance: Inheritance allows you to create a class hierarchy that reflects the relationships between Objects. For example, you might have a base Class Vehicle
containing common properties like name
and color
, and a method like move()
. You can then create subclasses like Car
, Boat
, and Plane
that inherit all the general attributes and behaviors of a vehicle but add their own unique features. This achieves efficient code reuse because you define common elements only once in the parent Class. Inheritance also makes it easy to extend a program; if you need a new type of vehicle, you simply create a new Class that extends Vehicle
instead of writing everything from scratch.
Simple Example: Let’s define a base Class Car
representing a regular car, and then a subclass ElectricCar
representing an electric car that inherits from Car
. In the subclass, we’ll add a battery property and a charging method, while still using the methods from the base Class:
<?php
// Base Class
class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
public function showColor() {
echo "The car color is " . $this->color;
}
}
// Subclass inheriting from Car
class ElectricCar extends Car {
public $batteryLevel = 0;
public function charge() {
$this->batteryLevel = 100;
}
}
// Creating and using an ElectricCar object
$ecar = new ElectricCar("yellow");
$ecar->charge();
$ecar->showColor(); // The car color is yellow
?>
In this example, ElectricCar
uses extends Car
, which means it automatically inherits the $color
property and the showColor()
method from the Car
Class. In ElectricCar
, we added the $batteryLevel
property and a charge()
method to set the battery to 100%. When we created an $ecar
object from ElectricCar
, we set its color to "yellow" at creation (using the inherited __construct
from Car
), called charge()
to fill the battery, and finally used the inherited showColor()
method to display the color. Notice that we never defined showColor()
in ElectricCar
, but the object was still able to use it because it was inherited.
Laravel Example: Frameworks like Laravel heavily rely on the concept of inheritance. For example, in Laravel, every Controller you create is actually a Class that inherits from a base Controller Class provided by the framework called Controller
. This base Class contains shared functionality that all controllers need (such as properties and middleware handling). When you create your application’s controller and make it extends Controller
, it automatically inherits all of those base features. The following code shows a simple example of a Laravel controller that inherits from the base Controller:
<?php
// Example of a Laravel Controller class
use App\Http\Controllers\Controller;
class PostController extends Controller {
public function show($id) {
// Code to display the post based on $id
}
}
?>
Here, PostController
extends App\Http\Controllers\Controller
(the base Class in the framework). This means PostController
automatically has access to everything provided by the base Class, and we only need to define the methods that handle our application’s logic (such as show()
to display a specific post). This approach saves us from writing repetitive code and allows for a clear, structured application architecture.
5- Polymorphism
Definition: Polymorphism refers to the ability of different Objects (that share a common ancestor) to respond differently to the same message or method call. In other words, we can call the same method name on objects from different classes, and each will have its own unique implementation of that method depending on its type. This allows you to write general programs that can handle various objects in a unified way. The term "Polymorphism" means that an Object can take on many forms depending on the context, while the interface (method name and parameters) remains the same.
Importance: Polymorphism provides great flexibility in program design. It allows you to use objects from different classes interchangeably as long as they share certain properties or behaviors (for example, they inherit from the same base Class or implement the same interface). This means you can write functions or algorithms that operate on the parent type or an interface without worrying about the specific type of the object being passed. The correct method implementation for that object will be executed automatically. The result is less need for long conditional statements to check an object’s type, and it becomes easier to add new types without changing the existing code.
Example: Let’s say we have a base Class Vehicle
with a move()
method, and we create several subclasses representing different types of vehicles (car, boat, plane). Each subclass will override the move()
method with behavior specific to that type of vehicle. We’ll write a general function that makes any vehicle move without knowing its type in advance, and it will use Polymorphism to call the correct behavior for each vehicle:
<?php
class Vehicle {
public function move() {
echo "The vehicle is moving";
}
}
class Car extends Vehicle {
public function move() {
echo "The car is driving on the road";
}
}
class Boat extends Vehicle {
public function move() {
echo "The boat is sailing in the water";
}
}
class Plane extends Vehicle {
public function move() {
echo "The plane is flying in the sky";
}
}
// Function that accepts any Vehicle and makes it move
function makeVehicleMove(Vehicle $v) {
$v->move();
}
// Testing Polymorphism:
makeVehicleMove(new Car()); // The car is driving on the road
makeVehicleMove(new Boat()); // The boat is sailing in the water
makeVehicleMove(new Plane()); // The plane is flying in the sky
?>
In this example, the classes Car
, Boat
, and Plane
all inherit from Vehicle
and override the move()
method to print a message specific to that type of vehicle. The general function makeVehicleMove(Vehicle $v)
accepts a parameter of type Vehicle
(meaning it can be any subclass of Vehicle
) and calls $v->move()
. Thanks to Polymorphism, PHP determines which move()
method to execute based on the actual type of the object passed in. This means that although we call makeVehicleMove()
in the same way for each vehicle, the result is different depending on whether it’s a car, boat, or plane. That’s the essence of Polymorphism.
6- Abstraction
Definition: Abstraction is a principle that focuses on the essential characteristics and behaviors of an object while hiding the unnecessary complex details to simplify the model. In the context of object-oriented programming, Abstraction means designing interfaces or abstract classes that define what an object should do without specifying how it does it. In other words, we separate the what from the how. Abstract classes and abstract methods provide no implementation details and leave it to the subclasses to define them.
Importance: Abstraction helps manage the complexity of large systems by dividing them into conceptual layers. Using Abstraction, we can define interfaces or abstract classes that act as contracts which any implementing classes must follow. This approach makes software more flexible and easier to modify since the implementation details in subclasses can change without affecting the parts of the program that interact with the abstract class or interface. Abstraction also encourages code reuse by separating the general concepts (abstractions) from the specific implementations. In PHP, Abstraction can be achieved using the abstract
keyword when defining an abstract class or method, or by using the interface
keyword to define a set of methods that implementing classes must provide.
Example: Let’s illustrate Abstraction using an interface Shape
that declares a method area()
(to calculate the area) without any implementation. Then we’ll create two classes: Circle
and Square
, both of which implement this interface but provide different implementations for the area()
method according to their own formulas. We can then use an object of type Shape
(in practice, passing in either a Circle or Square object) and call the area()
method without worrying about the internal details of how each shape’s area is calculated:
<?php
interface Shape {
public function area();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * pow($this->radius, 2);
}
}
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function area() {
return $this->side * $this->side;
}
}
// Example usage
$circle = new Circle(3);
$square = new Square(4);
echo $circle->area(); // 28.27 (approximate area of the circle)
echo $square->area(); // 16 (area of the square)
?>
Here, the Shape
interface defines the area()
method without providing any details. The Circle
and Square
classes both implement Shape
, meaning they are required to provide their own area()
method. Each class calculates the area in its own way: the circle uses the formula πr2 (pi times the radius squared), and the square uses the formula side * side
. In the usage example, we call $shape->area()
(whether the shape is a circle or a square) and get the correct result for each. This demonstrates the power of Abstraction: we can work with different shapes through a single shared interface without needing to know the specific calculation details for each one. Many parts of frameworks like Laravel are built on this concept, defining interfaces for different components and leaving it up to the actual application (or the developer) to provide the implementation that fits their needs.
Conclusion
The core concepts of Object-Oriented Programming in PHP are: Classes, Objects, Encapsulation, Inheritance, Polymorphism, and Abstraction. These principles are interconnected and together form the foundation of the object-oriented programming approach. By using Classes and Objects, we can build programs that are more organized and flexible. With Encapsulation, we protect our data, while Inheritance, Polymorphism, and Abstraction allow us to reuse code and write applications that can easily scale. Mastering these concepts is extremely important, especially when working on large projects or using modern frameworks like Laravel, which heavily relies on OOP in its architecture. Apply these principles in your own projects, and you will notice how your code becomes easier to understand and maintain as your application grows.
Blog
What’s New in ECMAScript 2025
Jun 30, 2025
What’s New in ECMAScript 2025 On June 25, 2025, Ecma International officially approved ES2025, adding several useful features: 1. 📦 Import At...
Laravel 12.21.0 – A Smart Update for Cleaner Queries and Stricter Validation
Aug 03, 2025
Laravel 12.21.0 introduces two game-changing features aimed at writing cleaner, more maintainable code. The update includes the new whereValueBetwe...
Comparison between Scopes + Traits × UseEloquentBuilder in Laravel
Jul 13, 2025
Laravel provides multiple ways to write reusable query logic. The two most common approaches are using Scopes with Traits or the newer #[UseEloquentBu...
React History – A Professional Developer’s Perspective
Jul 26, 2025
1. Origins: Born Inside Facebook In 2011, Facebook engineers faced the increasing complexity of building interactive UIs at scale. They developed...
React Native 0.80 & ExecuTorch: A Powerful Leap into Offline AI for Mobile Apps
Jul 28, 2025
🚀 What’s New in React Native 0.80? The React Native 0.80 release marks a pivotal moment in mobile development. This update not only enhances...
Laravel 12.16.0 - New Features for Developers
Jun 03, 2025
Laravel 12.16.0 - New Features for Developers 1. New Validation Rule: in_array_keys You can now validate that an array contains at least one of the...
