Challenge 1 — Solution
Task: Create an Animal class with a constructor setting $name, and a
method makeSound() that echoes a generic message. Create Cat and Cow
classes that extend it and override makeSound() with their own sound.
Create one of each and call makeSound() on both.
name} makes some generic animal sound.
";
}
}
class Cat extends Animal {
public function makeSound() {
echo "{$this->name} says Meow!
";
}
}
class Cow extends Animal {
public function makeSound() {
echo "{$this->name} says Moo!
";
}
}
$cat = new Cat("Whiskers");
$cow = new Cow("Bessie");
$cat->makeSound();
$cow->makeSound();
?>
Output:
Whiskers says Meow!
Bessie says Moo!
Notes:
- Both Cat and Cow extend Animal, inheriting its constructor (via the
protected $name property) without needing to redeclare it themselves.
- Each subclass overrides makeSound() with its own version - PHP always
uses the most specific override available for the object a method is
called on, so $cat->makeSound() runs Cat's own version, not Animal's
generic one.
- $name is declared protected (rather than private) specifically so
that Cat and Cow, as subclasses, can reference $this->name directly
inside their own overridden makeSound() methods - a private property
on Animal would not be accessible from a subclass at all.