PHP Abstract Class
In PHP, an abstract class is a class that cannot be instantiated and may contain abstract methods. Abstract classes are often used to define a blueprint for other classes, providing common functionality while allowing derived classes to implement specific details.
Syntax
abstract class AbstractClass {
// Abstract method declaration
abstract protected function abstractMethod();
// Regular method with implementation
public function concreteMethod() {
// Method implementation
}
}
Example
Here's an example of an abstract class in PHP:
abstract class Shape {
abstract protected function calculateArea();
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
protected function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
Explanation
In the example, Shape
is an abstract class with an abstract method calculateArea()
. The Circle
class extends Shape
and provides an implementation for the calculateArea()
method.
- Abstract classes are declared using the
abstract
keyword. - Abstract methods are declared using the
abstract
keyword and must be implemented by derived classes.
Use
Abstract classes in PHP are used for:
- Defining a common interface for multiple related classes.
- Enforcing a structure that derived classes must follow.
- Providing a level of abstraction for shared functionality.
Important Points
- Abstract classes cannot be instantiated directly; they are meant to be subclassed.
- Abstract methods must be implemented by any concrete (non-abstract) subclass.
- Abstract classes can have both abstract and regular (concrete) methods.
Summary
In summary, PHP abstract classes provide a way to define common functionality that should be shared among multiple classes while allowing each class to implement specific details. They contribute to code organization, reusability, and the creation of a structured class hierarchy.