PHP Abstract Class
An abstract class in PHP is a class that cannot be instantiated directly. It is meant to be extended by other classes that provide implementations for its abstract methods. Abstract methods are methods that are declared in the abstract class but do not have a body. Subclasses that extend the abstract class must provide implementations for these abstract methods.
Here’s a breakdown of how abstract classes work in PHP:
1. Defining an Abstract Class
To define an abstract class, use the abstract keyword before the class keyword. Inside an abstract class, you can have both abstract methods (methods without implementations) and regular methods (methods with implementations).
2. Defining Abstract Methods
Abstract methods are declared without a body and must be implemented by any non-abstract class that extends the abstract class.
3. Extending Abstract Classes
When a class extends an abstract class, it must provide implementations for all the abstract methods defined in the abstract class.
Example:
Here’s a basic example to illustrate abstract classes and methods:
<?php
// Define an abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract public function makeSound();
// Regular method
public function sleep() {
echo "Zzz...";
}
}
// Define a class that extends the abstract class
class Dog extends Animal {
// Provide implementation for the abstract method
public function makeSound() {
echo "Woof!";
}
}
// Define another class that extends the abstract class
class Cat extends Animal {
// Provide implementation for the abstract method
public function makeSound() {
echo "Meow!";
}
}
// Create instances of the subclasses
$dog = new Dog();
$cat = new Cat();
// Call the methods
$dog->makeSound(); // Outputs: Woof!
$dog->sleep(); // Outputs: Zzz...
$cat->makeSound(); // Outputs: Meow!
$cat->sleep(); // Outputs: Zzz...
?>
Explanation:
-
Abstract Class Animal:
- Contains an abstract method
makeSound(), which must be implemented by any subclass.
- Contains a regular method
sleep(), which is inherited by subclasses without needing to be redefined.
-
Subclasses Dog and Cat:
- Both
Dog and Cat extend Animal and provide implementations for the makeSound() method.
- They inherit the
sleep() method from the Animal class.
-
Creating Instances:
- You can create instances of
Dog and Cat, but you cannot create an instance of Animal directly because it is abstract.
This setup enforces a common interface for all subclasses while allowing each subclass to provide its own implementation of the abstract methods.