Abstract classes let you create a basic plan for other classes to follow. Abstract methods are like empty tasks that child classes must fill in.
Abstract classes and methods in PHP
<?php abstract class Animal { abstract public function makeSound(); public function sleep() { echo "Sleeping...\n"; } } class Dog extends Animal { public function makeSound() { echo "Bark!\n"; } } ?>
An abstract class is declared with the keyword abstract.
Abstract methods have no body and must be implemented by child classes.
<?php abstract class Vehicle { abstract public function startEngine(); } class Car extends Vehicle { public function startEngine() { echo "Car engine started\n"; } } class Bike extends Vehicle { public function startEngine() { echo "Bike engine started\n"; } } ?>
<?php abstract class Shape { abstract public function area(); } // Edge case: No child class created, so no object can be made from Shape // Trying to create Shape directly will cause an error. ?>
<?php abstract class Printer { abstract public function printDocument(); } class SimplePrinter extends Printer { public function printDocument() { echo "Printing document...\n"; } } // Edge case: If SimplePrinter does not implement printDocument, PHP will error. ?>
This program shows an abstract class Employee with an abstract method calculateSalary. Two child classes implement this method differently. We create objects and show their salaries.
<?php abstract class Employee { protected string $name; public function __construct(string $name) { $this->name = $name; } abstract public function calculateSalary(): float; public function display() { echo "Employee: {$this->name}\n"; } } class FullTimeEmployee extends Employee { private float $monthlySalary; public function __construct(string $name, float $monthlySalary) { parent::__construct($name); $this->monthlySalary = $monthlySalary; } public function calculateSalary(): float { return $this->monthlySalary; } } class PartTimeEmployee extends Employee { private float $hourlyRate; private int $hoursWorked; public function __construct(string $name, float $hourlyRate, int $hoursWorked) { parent::__construct($name); $this->hourlyRate = $hourlyRate; $this->hoursWorked = $hoursWorked; } public function calculateSalary(): float { return $this->hourlyRate * $this->hoursWorked; } } // Create employees $fullTimeEmployee = new FullTimeEmployee("Alice", 3000.00); $partTimeEmployee = new PartTimeEmployee("Bob", 20.00, 80); // Display and calculate salaries $fullTimeEmployee->display(); echo "Salary: $" . $fullTimeEmployee->calculateSalary() . "\n"; $partTimeEmployee->display(); echo "Salary: $" . $partTimeEmployee->calculateSalary() . "\n"; ?>
Time complexity: Implementing abstract methods does not affect runtime complexity; it is about design.
Space complexity: No extra space is used by abstract classes themselves.
Common mistake: Forgetting to implement all abstract methods in child classes causes errors.
Use abstract classes when you want to force child classes to have certain methods but also share some code.
Abstract classes provide a base plan that cannot be used directly.
Abstract methods are empty methods that child classes must fill in.
Child classes must implement all abstract methods or PHP will throw an error.
Practice
abstract class in PHP?Solution
Step 1: Understand abstract class concept
An abstract class is designed to be a base class that other classes extend but cannot be instantiated on its own.Step 2: Eliminate incorrect options
Options A, B, and D do not describe abstract classes correctly. PHP does not support multiple inheritance, and abstract classes cannot be instantiated directly.Final Answer:
To provide a base class that cannot be instantiated directly -> Option DQuick Check:
Abstract class = base class no direct objects [OK]
- Thinking abstract classes can be instantiated
- Confusing abstract classes with interfaces
- Believing abstract classes store data only
Solution
Step 1: Recall abstract method syntax
In PHP, abstract methods are declared with the keywordabstractbefore the function signature and have no body (no curly braces).Step 2: Check each option
abstract public function myMethod(); correctly declares an abstract method:abstract public function myMethod();. Options B and D have bodies or wrong order, and C uses incorrect syntax.Final Answer:
abstract public function myMethod(); -> Option AQuick Check:
Abstract method = abstract + no body [OK]
- Adding curly braces {} to abstract methods
- Wrong keyword order or missing 'abstract'
- Trying to implement method body in abstract method
abstract class Animal {
abstract public function sound();
}
class Dog extends Animal {
public function sound() {
return "Bark";
}
}
$dog = new Dog();
echo $dog->sound();Solution
Step 1: Understand class inheritance and method implementation
The abstract classAnimalhas an abstract methodsound(). The classDogextendsAnimaland implementssound()returning "Bark".Step 2: Check object creation and method call
We create an object ofDog(which is allowed) and callsound(). This returns "Bark" which is echoed.Final Answer:
Bark -> Option CQuick Check:
Implemented abstract method returns 'Bark' [OK]
- Trying to instantiate abstract class directly
- Forgetting to implement abstract method in child
- Expecting syntax error due to abstract method
abstract class Vehicle {
abstract public function startEngine();
}
class Car extends Vehicle {
// No implementation of startEngine()
}
$car = new Car();
$car->startEngine();Solution
Step 1: Check abstract method implementation
The abstract classVehicledeclares an abstract methodstartEngine(). The child classCardoes not implement this method.Step 2: Understand PHP rules for abstract methods
PHP requires all abstract methods to be implemented in child classes unless the child is also abstract. SinceCaris concrete and missing the method, this causes an error.Final Answer:
Class Car must implement abstract method startEngine() -> Option AQuick Check:
Missing abstract method implementation = error [OK]
- Forgetting to implement abstract methods in child
- Trying to instantiate abstract class directly
- Assuming abstract methods can have bodies
abstract class Shape {
abstract public function area();
}
class Square extends Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function area() {
return $this->side * $this->side;
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return 3.14 * $this->radius * $this->radius;
}
}
$shapes = [new Square(4), new Circle(3)];
foreach ($shapes as $shape) {
echo $shape->area() . " ";
}Solution
Step 1: Calculate area for Square
Square side is 4, so area = 4 * 4 = 16.Step 2: Calculate area for Circle
Circle radius is 3, so area = 3.14 * 3 * 3 = 28.26.Step 3: Understand output formatting
The code echoes each area followed by a space, so output is "16 28.26 " without newline.Final Answer:
16 28.26 -> Option BQuick Check:
Area calculations correct, output matches [OK]
- Confusing output formatting with newline
- Trying to instantiate abstract class Shape
- Incorrect area formulas
Ready to prove it?
Pass the test and this pattern moves unknown
