HOME HTML EDITOR C JAVA PHP

PHP OOP Abstract Classes

An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code. Its purpose is to provide a template that child classes must follow.

1. What is an Abstract Class?

Think of an abstract class as a "half-finished" blueprint. It defines what a class should do, but leaves the "how" to the child classes. You cannot create an object (instantiate) directly from an abstract class.

<?php
abstract class ParentClass {
  abstract public function someMethod();
}
?>

2. Rules for Abstract Classes

3. Practical Example

In this example, the parent class Car forces all child classes to define their own intro() method:

<?php
// Parent class
abstract class Car {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  abstract public function intro() : string;
}

// Child classes
class Audi extends Car {
  public function intro() : string {
    return "Choose German quality! I am an {$this->name}!";
  }
}

class Volvo extends Car {
  public function intro() : string {
    return "Proud to be Swedish! I am a {$this->name}!";
  }
}

$audi = new Audi("Audi");
echo $audi->intro();
?>

4. Abstract Classes vs. Interfaces

While they look similar, there is a key difference: Abstract classes can have properties and regular methods with code, whereas Interfaces can only define method names (until recently).

Feature Abstract Class Interface
Methods Can have both abstract and normal methods. All methods are abstract (by nature).
Properties Can have regular variables. Cannot have variables (only constants).
Inheritance A class can only extend one abstract class. A class can implement multiple interfaces.
When to use? Use an abstract class when you want to share code among several closely related classes (like different types of Cars). Use an interface when you want to define a common capability among unrelated classes.