Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects." In OOP, objects are instances of classes, which act as blueprints or templates for creating objects. This paradigm is designed to model real-world entities and their relationships in a software system, making it easier to manage and manipulate complex systems.
PHP Object-Oriented Programming (OOP)
In OOP, there are four fundamental principles, known as the Four Pillars of OOP:
Encapsulation
Encapsulation is the concept of bundling data (attributes) and the methods (functions) that operate on that data into a single unit, called a class. This unit hides the internal details of how it works, and you can only interact with it through a well-defined interface. This helps with data security and prevents unintended modifications.
class Car {
private $color; // Encapsulated attribute
public function setColor($newColor) { // Encapsulated method
$this->color = $newColor;
}
public function getColor() {
return $this->color;
}
}
Inheritance
Inheritance allows you to create a new class that inherits properties and behaviors from an existing class. This promotes code reuse and the creation of a hierarchy of related classes.
class SportsCar extends Car {
// SportsCar inherits attributes and methods from Car
}
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common base class. This enables you to write code that can work with objects in a more generic way, regardless of their specific types.
function displayInfo(Car $vehicle) {
echo "This vehicle is a " . get_class($vehicle) . " and it is " . $vehicle->getColor() . " in color.";
}
$myCar = new Car();
$mySportsCar = new SportsCar();
displayInfo($myCar);
displayInfo($mySportsCar);
Abstraction
Abstraction is the process of simplifying complex reality by modeling classes based on the essential features an object should have, while hiding the irrelevant details. It provides a clear separation between what an object does and how it's implemented.
abstract class Shape {
abstract public function calculateArea();
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
- In the above code, we have defined a Shape class as an abstraction, which defines a method calculateArea() that all shapes must implement. Then, we have a specific shape, Circle, which inherits from Shape and provides its own implementation of calculateArea().
These principles are the foundation of OOP, and they help in creating more organized, maintainable, and scalable code by promoting the use of classes, objects, and their relationships to model real-world systems in software.