extends and parent::
class Manager extends Employee makes Manager a subclass: it inherits every public and protected property and method of Employee, and can add its own or override inherited ones. PHP has single inheritance — one parent per class. parent::method() calls the parent's version, which is how an override extends behaviour instead of copying it. A child constructor must call parent::__construct() itself; PHP does not do it for you. The #[\Override] attribute (PHP 8.3) makes PHP check that a parent method with that name really exists.
<?php
declare(strict_types=1);
class Employee
{
public function __construct(
protected string $name,
protected float $salary,
) {}
public function describe(): string
{
return "{$this->name} earns {$this->salary}";
}
public function annualCost(): float
{
return $this->salary * 12;
}
}
class Manager extends Employee
{
private array $reports = [];
public function __construct(string $name, float $salary, private float $bonus)
{
parent::__construct($name, $salary); // let the parent set its part
}
public function addReport(Employee $e): void
{
$this->reports[] = $e;
}
#[\Override]
public function annualCost(): float
{
return parent::annualCost() + $this->bonus; // extend, do not repeat
}
#[\Override]
public function describe(): string
{
return parent::describe() . " and manages " . count($this->reports);
}
}
$dev = new Employee('Ravi', 90000);
$lead = new Manager('Asha', 150000, 200000);
$lead->addReport($dev);
echo $dev->describe(), "\n";
echo $lead->describe(), "\n";
echo $lead->annualCost(), "\n";
var_dump($lead instanceof Employee, $dev instanceof Manager);
echo get_parent_class($lead), "\n";Ravi earns 90000
Asha earns 150000 and manages 1
2000000
bool(true)
bool(false)
EmployeeA Manager is an Employee, so it can go anywhere an Employee is expected — including addReport(). That "is a" test is the one to apply before you reach for extends.
Remove the parent::__construct(...) line and call $lead->describe(). Which error do you get, and which property is it about?
final by default. The Design Patterns course shows the patterns this leads to.