Home › PHP Tutorial › PHP inheritance
PHP inheritance
Reuse and override behaviour in child classes.
A child class extends a parent and inherits its properties and methods. Mark members protected to share them with children but hide them from outside code.
Example code
<?php
class Animal {
public function __construct(protected string $name) {}
public function speak(): string {
return $this->name . " makes a sound";
}
}
class Dog extends Animal {
public function speak(): string {
return $this->name . " barks";
}
}
foreach ([new Animal("Cat"), new Dog("Rex")] as $a) {
echo $a->speak() . PHP_EOL;
}
?>