Inheritance lets one class extend another and reuse its code. The child gets all methods and properties of the parent. Use extends and call parent::__construct() to initialize the parent properly in the child class.
Inheritance
class Animal {
public function __construct(
protected string $name,
protected string $sound
) {}
public function speak(): string {
return "{$this->name} says {$this->sound}";
}
public function getName(): string {
return $this->name;
}
}
class Dog extends Animal {
public function __construct(string $name) {
parent::__construct($name, "Woof");
}
public function fetch(): string {
return "{$this->name} fetches the ball!";
}
// Override parent method
public function speak(): string {
return parent::speak() . "!";
}
}
$dog = new Dog("Rex");
echo $dog->speak(); // Rex says Woof!
echo $dog->fetch(); // Rex fetches the ball!