php · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Dinner is served. Or is it? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
abstract class Meal {
abstract public function name(): string;
public function serve(): string {
return "Here is your " . $this->name() . ".";
}
}
class Soup extends Meal {
public function name(): string { return "tomato soup"; }
}
$dinner = new Meal();
echo $dinner->serve() . "\n";
your turn
Your turn. Teach a new class to shout.
Choose a class name, like Pirate, and type it in both name blanks. Then type the words it says. The parent turns them into a shout for you.
fix it
The sales report has lost its title. Fix it.
- The error says
$title must not be accessed before initialization. Which constructor is meant to fill in$title? - The child writes its own constructor, which overrides the parent's. The parent's one, the only one that sets
$title, never runs. - Inside the curly brackets on line 12, add
parent::__construct("Sales");, then run it.
nailed it
you wrote classes with blanks to fill. :D
- An abstract class shares code but is never built with
new. - An abstract method has no body, so every child must write one.
- A child's own constructor must call
parent::__constructitself.
new words in your collection
- abstract class
- abstract method
This lesson isn’t saved. A free account remembers every lesson you finish.