๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Abstract Classes

An abstract class is a class that cannot be used to make objects directly. It holds shared code and names methods that each child must write.

A child fills the abstract method

Shape is abstract and names an abstract method called name. The plain kind method carries shared code, and Circle writes the name method.

<?php
abstract class Shape {
  abstract public function name();
  public function kind() {
    echo "I am a shape\n";
  }
}
class Circle extends Shape {
  public function name() {
    echo "Circle\n";
  }
}
$circle = new Circle();
$circle->kind();
$circle->name();

Two children fill it in two ways

Circle and Square both extend Shape. Each child writes the name method in its own way, and the two lines differ.

<?php
abstract class Shape {
  abstract public function name();
}
class Circle extends Shape {
  public function name() {
    echo "Circle\n";
  }
}
class Square extends Shape {
  public function name() {
    echo "Square\n";
  }
}
$circle = new Circle();
$circle->name();
$square = new Square();
$square->name();

Making an object from an abstract class fails

This program tries to make an object from Shape itself. PHP stops with a fatal error, and the line below states that error.

<?php
abstract class Shape {
  abstract public function name();
}
$shape = new Shape();

Example

<?php
abstract class Shape {
  abstract public function area();
}
class Rectangle extends Shape {
  public $width = 4;
  public $height = 3;
  public function area() {
    echo "Rectangle: " . $this->width * $this->height . "\n";
  }
}
class Triangle extends Shape {
  public $base = 6;
  public $height = 4;
  public function area() {
    echo "Triangle: " . $this->base * $this->height / 2 . "\n";
  }
}
$rectangle = new Rectangle();
$rectangle->area();
$triangle = new Triangle();
$triangle->area();

Key points

  • The word abstract before class marks the class as abstract.
  • An abstract method names a method and gives it no body.
  • A child of an abstract class must write every abstract method it takes.
  • Plain methods in an abstract class carry shared code to every child.
  • Making an object from an abstract class stops the program with a fatal error.

In this example, Shape names an abstract area method and holds no area code. Rectangle multiplies its width by its height and prints 12. Triangle multiplies its base by its height, halves the result, and prints 12 too.

Note

An abstract class can hold properties and a constructor like a plain class.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a program tries to make an object from an abstract class?