extendsPHP inheritance lets a child class reuse properties and methods from a parent class using the extends keyword. When specialized classes share common fields or behavior—like EmailNotification and SmsNotification extending Notification—inheritance removes repeated boilerplate.
parent::A child class inherits all public and protected members from its parent and can override any non-final method to customize its behavior. Use parent::methodName() inside an overridden method when you want to keep the parent's setup logic and add extra steps.
<?php
declare(strict_types=1);
class Notification
{
public function __construct(protected string $recipient) {}
public function send(string $message): string
{
return "Prepared notification for {$this->recipient}: {$message}";
}
}
final class EmailNotification extends Notification
{
public function __construct(string $recipient, private string $subject)
{
parent::__construct($recipient);
}
public function send(string $message): string
{
$base = parent::send($message);
return "{$base} [Subject: {$this->subject}]";
}
}
$mail = new EmailNotification('[email protected]', 'Invoice Ready');
echo $mail->send('Your invoice #402 is attached.') . PHP_EOL;
final and Favoring CompositionMarking a class or method final prevents subclasses from overriding it and breaking assumptions. Whenever a class needs behavior from several unrelated sources—such as logging plus caching—prefer composition (injecting helper services) over deep multi-level inheritance trees.
UserController should never extend DatabaseHelper. Inject a service class instead; use extends only for genuine "is-a" relationships.protected parent method to private in a child class causes a fatal error. Overrides must stay equally visible or become more open (protected to public).No. A PHP class can extends only one parent class directly. To share methods across unrelated classes, use traits or implement multiple interfaces.
final class prevent?Adding final before class blocks any other class from extending it, which is common for value objects and security-sensitive services.
private properties of its parent?No. private members stay invisible even to child classes. Use protected or a protected getter method when subclasses need access.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.