×

php · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a form with blanks each child must fill in.

Some parents are too general to exist on their own. Nobody owns a plain shape, only circles and squares. Mark the parent abstract class and it can still share real code with its children, but new Shape() is refused with an Error.

An abstract class can also hold an : a name, parameters and a return type, but no body at all. Every child must write it. Here, the parent knows how to describe any shape, but only each child knows how to work out its own area.

<?php
abstract class Shape {
    abstract public function area(): float;

    public function describe(): string {
        return "My area is " . $this->area();
    }
}
class Square extends Shape {
    public function __construct(private float $side) {}
    public function area(): float {
        return $this->side * $this->side;
    }
}
$tile = new Square(3);
echo $tile->describe() . "\n";

describe() is written in the parent, yet $this->area() runs the child's version, because $this is the square.