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.
- Contains an abstract method
-
Subclasses
Dog
andCat
:- Both
Dog
andCat
extendAnimal
and provide implementations for themakeSound()
method. - They inherit the
sleep()
method from theAnimal
class.
- Both
-
Creating Instances:
- You can create instances of
Dog
andCat
, but you cannot create an instance ofAnimal
directly because it is abstract.
- You can create instances of
This setup enforces a common interface for all subclasses while allowing each subclass to provide its own implementation of the abstract methods.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.