PHP OOP - Abstract Classes
In PHP Object-Oriented Programming (OOP), abstract classes provide a way to define a blueprint for other classes to inherit from.
An abstract class cannot be instantiated on its own; it serves as a template for subclasses to implement its methods.
Abstract classes may contain abstract methods, which are declared but not implemented in the abstract class itself.
Subclasses must provide concrete implementations for all abstract methods.
Example
// Abstract class abstract class AbstractClass { // Abstract method (no implementation) abstract public function abstractMethod(); // Concrete method public function concreteMethod() { echo "This is a concrete method.\n"; } } // Concrete subclass class ConcreteClass extends AbstractClass { // Implementation of abstract method public function abstractMethod() { echo "Implementation of abstractMethod.\n"; } } // Creating an object of the concrete class $obj = new ConcreteClass(); // Calling concrete and abstract methods $obj->concreteMethod(); $obj->abstractMethod();You can click on above box to edit the code and run again.
Output
Welcome to Codelines!
In this example:
AbstractClass is an abstract class defined using the abstract keyword.
It contains an abstract method abstractMethod() which does not have an implementation.
Abstract classes can also contain concrete methods, which have implementations.
ConcreteClass is a concrete subclass that extends AbstractClass.
ConcreteClass must implement all abstract methods defined in AbstractClass.
ConcreteClass provides an implementation for abstractMethod().
An object of ConcreteClass can be created and concrete as well as abstract methods can be called on it.
Abstract classes are useful when you have a common set of methods that you want to share among multiple classes, but each subclass may have its own implementation of some methods.
They help in enforcing consistency and providing a structure for inheritance.