Advertisement
Google Ad Slot: content-top
PHP OOP - Abstract Classes
PHP - What are Abstract Classes and Methods?
An abstract class in PHP is a class that cannot be instantiated directly. This means you can't create objects straight from an abstract class.
An abstract class is a class that contains at least one abstract method and it does not have body. The body is provided by the subclass (inherited from).
An abstract class or method is defined with the abstract keyword:
Key Features of Abstract Classes:
✔ Declared using the abstract keyword.
✔ Cannot be instantiated directly.
✔ Can contain both abstract and regular methods.
✔ Child classes must implement all abstract methods.
Syntax
abstract class ClassName {
abstract public function methodName(); // Abstract method (must be implemented)
public function regularMethod() {
// Regular method (optional to override)
}
}
Rules for Implementing Abstract Methods in Child Classes
- Same Method Name
- The child class must define the method with the exact same name as in the abstract class.
- Access Modifier Restriction
- The child class method cannot have a more restricted access modifier than the abstract method.
- If an abstract method is
protected, the child class method can beprotectedorpublic, but notprivate.
- Same Number of Required Arguments
- The child class must implement the abstract method with the same number of required parameters.
- However, the child class can add optional parameters.
Let's look at an example:
Explanation:
1. Vehicle (Abstract Class)
- Defines common properties (
brand,speed). - Contains an abstract method
startEngine()(to be implemented by child classes).
2. Car (Concrete Class)
- Extends
Vehicleand implementsstartEngine().
3. Creating an Object
Caris instantiated and methods are called.
PHP - More Abstract Class Examples
Let's look at another example where the abstract method has an argument:
In this example, we'll define an abstract class Vehicle with an abstract method startEngine($keyType), where:
- The abstract method has one required parameter (
$keyType). - The child class
Caradds two optional parameters ($fuelLevel,$engineMode).