Tools
Log in
English

Learn to codePHP

PHP inheritance

Based on PHP 8.3

PHP inheritance with extends, parent:: and final, shown with parcel fees.

In one line

Inheritance takes the properties and methods of an existing class (the parent) and lets you write only what differs. A PHP class extends at most one parent with extends, and an overriding method reaches the parent version through parent::.

Why you need it

Writing every parcel type from scratch copies the destination, the weight, the weight-based price and the label format into every class. When the weight limit moves from 2000 g to 2500 g, every file needs an edit.

Put the shared rule in Parcel once and write only the differences: express adds 2500, fragile doubles the price. A new limit is then a one-line change in the parent.

Everyday picture

Picture the parcel form at a convenience store. The basic form has boxes for destination, weight and price; the express form is the same form with one extra box for the delivery slot. Keeping the basic boxes and adding new ones is inheritance.

Example code

main.php · 59 lines
<?phpdeclare(strict_types=1); class Parcel{    public function __construct(        protected string $to,        protected int $grams,    ) {    }     public function fee(): int    {        $fee = $this->grams > 2000 ? 4500 : 3000;        return $fee;    }     public function label(): string    {        return sprintf('%-6s %5dg %5d won', $this->to, $this->grams, $this->fee());    }} class ExpressParcel extends Parcel{    public function __construct(string $to, int $grams, private string $slot)    {        parent::__construct($to, $grams);    }     public function fee(): int    {        return parent::fee() + 2500;    }     public function label(): string    {        return parent::label() . " ({$this->slot})";    }} final class FragileParcel extends Parcel{    public function fee(): int    {        $fee = parent::fee() * 2;        return $fee;    }} $list = [    new Parcel('Busan', 800),    new ExpressParcel('Seoul', 2400, 'by 9pm'),    new FragileParcel('Jeju', 1200),];foreach ($list as $p) {    echo $p->label(), "\n";}var_dump($list[1] instanceof Parcel, $list[2] instanceof ExpressParcel);

When to use it

  • The sentence "an express parcel is a parcel" sounds natural
  • You reuse most of the parent rules and change only a few
  • If a class should not be extended further, mark it final class. That prevents deep inheritance chains from growing by accident.

A PHP class has exactly one parent at most. To share the same methods across unrelated classes, use a trait (see composition and static); to share only a contract, use an interface (see polymorphism).

Common mistakes

Forgetting parent::__construct() in the child

Unlike Java, PHP does not call the parent constructor for you when the child has its own. $to, which the parent was meant to fill, stays uninitialized and reading it fails. Call it yourself at the top of the child constructor.

Wrong

class Parcel{    public function __construct(protected string $to)    {    }} class ExpressParcel extends Parcel{    public function __construct(string $to, private string $slot)    {    }     public function show(): string    {        return "{$this->to} {$this->slot}";    }} echo (new ExpressParcel('Seoul', '9pm'))->show(), "\n";

When you run itFatal error: Uncaught Error: Typed property Parcel::$to must not be accessed before initialization

Fixed

class Parcel{    public function __construct(protected string $to)    {    }} class ExpressParcel extends Parcel{    public function __construct(string $to, private string $slot)    {        parent::__construct($to);    }     public function show(): string    {        return "{$this->to} {$this->slot}";    }} echo (new ExpressParcel('Seoul', '9pm'))->show(), "\n";

When you run itSeoul 9pm

Adding a required parameter to an override

A child must work wherever the parent is expected, so the override has to accept a plain fee() call. Give the new parameter a default. PHP checks this when it loads the class, before anything runs.

Wrong

class Parcel{    public function fee(): int    {        return 3000;    }} class HeavyParcel extends Parcel{    public function fee(int $extra): int    {        return 3000 + $extra;    }}

What PHP saysFatal error: Declaration of HeavyParcel::fee(int $extra): int must be compatible with Parcel::fee(): int

Fixed

class Parcel{    public function fee(): int    {        return 3000;    }} class HeavyParcel extends Parcel{    public function fee(int $extra = 1500): int    {        return parent::fee() + $extra;    }} echo (new HeavyParcel())->fee(), "\n";

When you run it4500

Trying to extend a final class

final means the class is not meant to be extended. Wrap it instead (composition), as in the fixed code, or agree with its author to remove final if you truly need a subclass.

Wrong

final class FragileParcel{} class GlassParcel extends FragileParcel{}

What PHP saysFatal error: Class GlassParcel cannot extend final class FragileParcel

Fixed

final class FragileParcel{    public function __construct(public readonly string $note = 'handle with care')    {    }} final class GlassParcel{    public function __construct(private FragileParcel $base = new FragileParcel())    {    }     public function note(): string    {        return $this->base->note . ', glass';    }} echo (new GlassParcel())->note(), "\n";

When you run ithandle with care, glass

Check yourself

Question 1

Inside ExpressParcel::fee(), what does parent::fee() call?

Show the answer

Answer: 3. It calls `fee()` from the parent `Parcel` parent:: calls the method from the direct parent class. Even after overriding, the child can reuse the parent calculation and build on it. $this is still the child object.

Question 2

What does fee() return for a 500 g express parcel?

$p = new ExpressParcel('Ulsan', 500, 'noon');echo $p->fee(), "\n";

Show the answer

Answer: 2. 5500 The parent rule gives 3000 for 2000 g or less, and express adds 2500, so 5500.

Questions people ask

Is the parent constructor called automatically?

Not when the child has its own constructor. Call parent::__construct() yourself inside it.

Can a PHP class have several parents?

No, extends takes one class. Use a trait to share code across classes and an interface to share a contract.

When should I use final?

On classes you do not intend to be extended and on methods that must not be overridden. It keeps inheritance chains from growing by accident.