Junior — Middle
What does using abstract classes entail and what are the advantages or disadvantages of their use?
sobes.tech AI
Answer from AI
Abstract classes in PHP are classes that cannot be instantiated directly and serve as templates for other classes. They can contain both implemented methods and abstract methods (without implementation), which must be implemented by child classes.
Advantages:
- Allow setting a common interface and basic logic for a group of related classes.
- Provide partial implementation, reducing code duplication.
- Help structure code and maintain architectural integrity.
Disadvantages:
- Rigid hierarchy that can complicate code extension and modification.
- PHP lacks multiple inheritance, so a class can only inherit from one abstract class, which limits flexibility.
Example:
abstract class Animal {
abstract public function makeSound();
public function eat() {
echo "Eating...";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark!";
}
}
$dog = new Dog();
$dog->makeSound(); // Outputs: Bark!
$dog->eat(); // Outputs: Eating...
In this example, the abstract class defines the mandatory method makeSound(), and also implements the eat() method, which is inherited.