Bird
Raised Fist0
PHPprogramming~5 mins

Abstract classes and methods in PHP

Choose your learning style10 modes available
Introduction

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.

When you want to make sure certain methods exist in all child classes.
When you have a general idea but want child classes to provide specific details.
When you want to prevent creating objects from a base class directly.
When you want to share some code but force other parts to be customized.
When designing a system with different types of similar objects.
Syntax
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.

Examples
Different child classes implement the abstract method in their own way.
PHP
<?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";
    }
}
?>
You cannot create an object from an abstract class directly.
PHP
<?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.
?>
Child classes must implement all abstract methods or PHP will throw an error.
PHP
<?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.
?>
Sample Program

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
<?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";
?>
OutputSuccess
Important Notes

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.

Summary

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

(1/5)
1. What is the main purpose of an abstract class in PHP?
easy
A. To store data without any methods
B. To create objects directly without any child classes
C. To allow multiple inheritance in PHP
D. To provide a base class that cannot be instantiated directly

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    To provide a base class that cannot be instantiated directly -> Option D
  4. Quick Check:

    Abstract class = base class no direct objects [OK]
Hint: Abstract classes can't create objects directly [OK]
Common Mistakes:
  • Thinking abstract classes can be instantiated
  • Confusing abstract classes with interfaces
  • Believing abstract classes store data only
2. Which of the following is the correct way to declare an abstract method in a PHP abstract class?
easy
A. abstract public function myMethod();
B. public function myMethod() {}
C. function abstract myMethod();
D. public abstract myMethod() {}

Solution

  1. Step 1: Recall abstract method syntax

    In PHP, abstract methods are declared with the keyword abstract before the function signature and have no body (no curly braces).
  2. 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.
  3. Final Answer:

    abstract public function myMethod(); -> Option A
  4. Quick Check:

    Abstract method = abstract + no body [OK]
Hint: Abstract methods have no body and use 'abstract' keyword [OK]
Common Mistakes:
  • Adding curly braces {} to abstract methods
  • Wrong keyword order or missing 'abstract'
  • Trying to implement method body in abstract method
3. What will be the output of the following PHP code?
abstract class Animal {
    abstract public function sound();
}

class Dog extends Animal {
    public function sound() {
        return "Bark";
    }
}

$dog = new Dog();
echo $dog->sound();
medium
A. No output
B. Fatal error: Cannot instantiate abstract class Animal
C. Bark
D. Syntax error

Solution

  1. Step 1: Understand class inheritance and method implementation

    The abstract class Animal has an abstract method sound(). The class Dog extends Animal and implements sound() returning "Bark".
  2. Step 2: Check object creation and method call

    We create an object of Dog (which is allowed) and call sound(). This returns "Bark" which is echoed.
  3. Final Answer:

    Bark -> Option C
  4. Quick Check:

    Implemented abstract method returns 'Bark' [OK]
Hint: Only child classes can be instantiated, output from implemented method [OK]
Common Mistakes:
  • Trying to instantiate abstract class directly
  • Forgetting to implement abstract method in child
  • Expecting syntax error due to abstract method
4. Identify the error in the following PHP code:
abstract class Vehicle {
    abstract public function startEngine();
}

class Car extends Vehicle {
    // No implementation of startEngine()
}

$car = new Car();
$car->startEngine();
medium
A. Class Car must implement abstract method startEngine()
B. Cannot instantiate abstract class Vehicle
C. Method startEngine() should not be abstract
D. No error, code runs fine

Solution

  1. Step 1: Check abstract method implementation

    The abstract class Vehicle declares an abstract method startEngine(). The child class Car does not implement this method.
  2. 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. Since Car is concrete and missing the method, this causes an error.
  3. Final Answer:

    Class Car must implement abstract method startEngine() -> Option A
  4. Quick Check:

    Missing abstract method implementation = error [OK]
Hint: All abstract methods must be implemented in child classes [OK]
Common Mistakes:
  • Forgetting to implement abstract methods in child
  • Trying to instantiate abstract class directly
  • Assuming abstract methods can have bodies
5. Given the abstract class and two child classes below, what will be the output?
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() . " ";
}
hard
A. 62.82 61
B. 16 28.26
C. Error: Cannot instantiate abstract class Shape
D. 6 28.26

Solution

  1. Step 1: Calculate area for Square

    Square side is 4, so area = 4 * 4 = 16.
  2. Step 2: Calculate area for Circle

    Circle radius is 3, so area = 3.14 * 3 * 3 = 28.26.
  3. Step 3: Understand output formatting

    The code echoes each area followed by a space, so output is "16 28.26 " without newline.
  4. Final Answer:

    16 28.26 -> Option B
  5. Quick Check:

    Area calculations correct, output matches [OK]
Hint: Calculate each area, watch for spaces and no newline [OK]
Common Mistakes:
  • Confusing output formatting with newline
  • Trying to instantiate abstract class Shape
  • Incorrect area formulas
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard