What is an abstract class in PHP

An abstract class in PHP is a class that cannot be instantiated on its own and is meant to be inherited by other classes. It can contain abstract methods, which are methods declared without a body that must be implemented by subclasses, as well as regular methods that may have implementations. This structure allows for defining a common interface and shared functionalities across different subclasses.

Abstract classes are useful in scenarios where you want to provide a common base for other classes that share certain common traits but also require specific implementations.

Here's an example of using an abstract class in PHP:

<?php abstract class Animal { // Abstract method abstract protected function makeSound(); // Regular method public function sleep() { return "Sleeping..."; } } class Dog extends Animal { public function makeSound() { return "Bark"; } } class Cat extends Animal { public function makeSound() { return "Meow"; } } $dog = new Dog(); echo $dog->makeSound(); // Outputs: Bark echo $dog->sleep(); // Outputs: Sleeping... $cat = new Cat(); echo $cat->makeSound(); // Outputs: Meow echo $cat->sleep(); // Outputs: Sleeping... ?>

abstract class PHP inheritance encapsulation polymorphism