PHP Inheritance and Interfaces
ExamplePHP
<?php
interface Speaker {
public function speak(): string;
}
abstract class Animal implements Speaker {
public function __construct(protected string $name) {}
}
class Dog extends Animal {
public function speak(): string { return "{$this->name} says woof"; }
}
class Cat extends Animal {
public function speak(): string { return "{$this->name} says meow"; }
}
foreach ([new Dog("Rex"), new Cat("Tom")] as $pet) {
echo $pet->speak(), "\n";
}Output
Rex says woof Tom says meow
Quick check
Which keyword makes a class inherit from another?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.