php · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A child class inherits everything from its parent, then adds more.
Dogs and cats are both animals. With you write the shared parts once in an Animal class, then write class Dog extends Animal. Dog is the child, Animal the parent, and every dog gets the parent's properties and methods for free.
A child can a method by writing one with the same name, and its version wins. Inside it, parent::describe() still runs the parent's version, so you can add to it instead of starting again.
private hides members even from children. Use when children need them but the outside world does not.
<?php
class Animal {
public function __construct(protected string $name) {}
public function describe(): string {
return "$this->name is an animal";
}
}
class Dog extends Animal {
public function describe(): string {
return parent::describe() . " that loves walks";
}
}
$rex = new Dog("Rex");
echo $rex->describe() . "\n"; Write parent classes above their children and use classes below their definitions, so PHP always knows a class before it needs it.
guess first
A bike and a plain vehicle. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Vehicle {
public function __construct(protected int $wheels) {}
public function info(): string {
return "$this->wheels wheels";
}
}
class Bike extends Vehicle {
public function info(): string {
return "A bike with $this->wheels wheels";
}
}
foreach ([new Bike(2), new Vehicle(4)] as $ride) {
echo $ride->info() . "\n";
}
your turn
Your turn. Open a bakery on the high street.
Make Bakery extend Shop, start its welcome with the parent's welcome, then pick a bake to recommend and a name for the bakery.
fix it
Tom cannot purr. Can you work out why?
- The error says
Undefined property: Cat::$name. The name is stored, so why can the child not see it? privatemeans only the class that wrote it,Animal, may touch it. Children are kept out too.- On line 3, change
privatetoprotected, then run it.
nailed it
your classes have families now. :D
extendsgives a child class everything its parent has.- Override a method by writing one with the same name.
protectedlets children in but keeps outsiders out.
new words in your collection
- inheritance
- override
- protected
This lesson isn’t saved. A free account remembers every lesson you finish.