×

php · level 3 · unit 2 · lesson 1

  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

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.