Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects, which are instances of classes. PHP, being an object-oriented scripting language, allows developers to create and manipulate objects, making code more organized, reusable, and easier to maintain. In this guide, we'll introduce you to fundamental OOP concepts in PHP, including classes, objects, inheritance, encapsulation, and polymorphism, with examples.
Classes and Objects
Classes
A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have. In PHP, a class is declared using the class
keyword.
// Define a class
class Car {
// Properties (attributes)
public $brand;
public $model;
public $color;
// Constructor method
public function __construct($brand, $model, $color) {
$this->brand = $brand;
$this->model = $model;
$this->color = $color;
}
// Method
public function displayInfo() {
echo "Brand: $this->brand, Model: $this->model, Color: $this->color";
}
}
?>
Objects
An object is an instance of a class. It represents a specific entity with its own set of properties and behaviors. In PHP, objects are created using the new
keyword followed by the class name, optionally passing arguments to the constructor if defined.
// Create an object of the Car class
$car1 = new Car("Toyota", "Camry", "Red");
$car2 = new Car("Honda", "Civic", "Blue");
// Call the method to display car information
$car1->displayInfo(); // Output: Brand: Toyota, Model: Camry, Color: Red
$car2->displayInfo(); // Output: Brand: Honda, Model: Civic, Color: Blue
?>
Inheritance
Inheritance is a mechanism in OOP where a class (subclass or derived class) inherits properties and methods from another class (superclass or base class). It promotes code reusability and allows the creation of a hierarchy of classes.
// Define a superclass
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sound() {
echo "Animal sound";
}
}
// Define a subclass that inherits from Animal
class Dog extends Animal {
public function sound() {
echo "Bark";
}
}
// Create objects of both classes
$animal = new Animal("Animal");
$dog = new Dog("Dog");
// Call the sound method
$animal->sound(); // Output: Animal sound
$dog->sound(); // Output: Bark
?>
Encapsulation
Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit, called a class. It hides the internal state of an object and only exposes the necessary functionalities through methods, providing better control over access to data and preventing direct manipulation.
// Define a class with encapsulation
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
public function deposit($amount) {
$this->balance += $amount;
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
} else {
echo "Insufficient funds";
}
}
public function getBalance() {
return $this->balance;
}
}
// Create an object of the BankAccount class
$account = new BankAccount(1000);
// Deposit and withdraw money
$account->deposit(500);
$account->withdraw(200);
// Get the current balance
echo "Current balance: $" . $account->getBalance(); // Output: Current balance: $1300
?>
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility in code design and promotes code reuse by allowing methods to behave differently based on the object's type.
// Define a superclass
class Shape {
public function calculateArea() {
return 0;
}
}
// Define subclasses that inherit from Shape
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
class Rectangle extends Shape {
private $length;
private $width;
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}
public function calculateArea() {
return $this->length * $this->width;
}
}
// Create objects of both classes
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
// Call the calculateArea method
echo "Area of the circle: " . $circle->calculateArea(); // Output: Area of the circle: 78.539816339745
echo "Area of the rectangle: " . $rectangle->calculateArea(); // Output: Area of the rectangle: 24
?>
Practice Excercise Practice now