PHP Abstract Classes – Create Blueprints for Your Classes 🚀
An abstract class in PHP is a class that serves as a blueprint for other classes. It can have both fully implemented methods and abstract methods (which must be defined in child classes).
Abstract classes cannot be instantiated directly. Instead, they are meant to be extended by child classes.
🔹 Why Use Abstract Classes?
- Ensures that all child classes follow a specific structure.
- Can include both implemented and abstract (unimplemented) methods.
- Promotes code reusability and maintainability.
📝 Example 1: Defining & Extending an Abstract Class
Here, we create an abstract class Animal
with an abstract method makeSound()
. Child classes must define this method.
<?php // Defining an abstract class abstract class Animal { abstract public function makeSound(); // Must be implemented in child classes public function eat() { return "Munch munch... 🍽️"; // A regular method } } // Extending the abstract class class Dog extends Animal { public function makeSound() { return "Woof! Woof! 🐶"; } } class Cat extends Animal { public function makeSound() { return "Meow! 🐱"; } } // Creating objects $dog = new Dog(); $cat = new Cat(); echo $dog->makeSound(); // Output: Woof! Woof! echo "<br>"; echo $cat->makeSound(); // Output: Meow! echo "<br>"; echo $dog->eat(); // Output: Munch munch... ?>
Notice how the makeSound()
method must be implemented in all child classes, but they can also use the eat()
method from the abstract class.
🔹 Abstract Classes with Constructors
Abstract classes can have constructors to initialize properties.
📝 Example 2: Abstract Class with a Constructor
<?php abstract class Vehicle { protected $brand; public function __construct($brand) { $this->brand = $brand; } abstract public function getBrand(); } // Extending abstract class class Car extends Vehicle { public function getBrand() { return "Car brand: " . $this->brand; } } $car = new Car("Toyota"); echo $car->getBrand(); // Output: Car brand: Toyota ?>
Here, the constructor initializes the $brand
property, which the child class uses.
🔹 Abstract vs. Interfaces: What’s the Difference?
Feature | Abstract Classes | Interfaces |
---|---|---|
Method Implementation | Can have both implemented & abstract methods | Cannot have implemented methods (only method signatures) |
Properties | Can have properties | Cannot have properties |
Usage | Used when classes share common behavior | Used when multiple classes follow the same structure |
Extensibility | A class can extend only one abstract class | A class can implement multiple interfaces |
🎯 Key Takeaways
abstract
→ Defines unimplemented methods for child classes.- Abstract classes cannot be instantiated.
- Can have both abstract and regular methods.
- Child classes must implement all abstract methods.
📝 Practice Time!
Create an abstract class Shape with an abstract method calculateArea()
. Then, create Circle and Rectangle classes that implement this method. 🎨