Back to questions
JuniorTheoryCommon
What does the program print?
<?php
class Animal
{
public function speak(): string { return 'hum'; }
}
class Dog extends Animal
{
public function speak(): string { return 'woof'; }
public function talk(): string { return parent::speak() . '!'; }
}
echo (new Dog())->speak(), ' ', (new Dog())->talk(), "\n";woof hum!
- Expecting
parent::speak()to run the override, like$this->speak():parent::always calls the parent class's version, so insideDogit still returnshum. - Treating a method with the parent's name as a redeclaration: a child class may override any parent method that is not
final, and its objects then use the child's version.
- What does
$this->speak()insideAnimalcall when the object is aDog? - Why must a child constructor call
parent::__construct()itself?