Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 147 ยท Object-Oriented PHP

Inheritance

Learn PHP inheritance: extends, overriding, parent::, protected members, constructor inheritance, final, signature rules, Liskov and the Override attribute.

Often several classes share most of their code. A shop sells physical products, digital downloads and gift cards: all have a name and a price, all print a label, but each calculates shipping differently. Copying the shared code into three classes means fixing every bug three times. Inheritance lets one class build on another: a child class (or subclass) extends a parent class (or base class) and automatically gets its properties and methods, then adds or changes what it needs.

This lesson covers extends, overriding methods, calling the parent's version with parent::, the protected visibility, how constructors are inherited, the rules PHP enforces for method signatures, final, the PHP 8.3 #[\Override] attribute, and the design rule that keeps class hierarchies sane: the Liskov substitution principle.

It builds on Classes, Properties and Methods and Constructors and Destructors.

extends

Write extends ParentName after the class name. The child then has every public and protected member of the parent as if it had declared them itself:

PHP A child class inherits and adds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

DigitalProduct declared only one method, yet it has a constructor, two properties and label() from Product. The instanceof checks show the key idea: a child object is also an instance of its parent. Anywhere a Product is expected (say, a function function addToCart(Product $item)), a DigitalProduct is accepted.

PHP supports single inheritance: a class can extend only one parent. A parent can have its own parent, forming a chain (GiftCard extends DigitalProduct extends Product). To share code across unrelated classes, use interfaces and traits.

Overriding methods

A child can override an inherited method by declaring a method with the same name. Calls on the child object then run the child's version. Digital products don't ship, so:

PHP Overriding and parent::

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two things happened:

  • shippingCents() replaces the parent's logic completely.
  • label() extends it: parent::label() calls the parent's version, and the child adds to the result. parent:: always means "the class I extend", and you can use it for any inherited method, not just the one being overridden.

Notice totalCents(). It's defined only in Product, and it calls $this->shippingCents(). For the digital product, $this is a DigitalProduct, so the child's override runs and the total has no shipping. This is polymorphism: the same call ($item->totalCents()) behaves correctly for each kind of object, and the loop doesn't need any if checks for product types.

protected: shared with children

The three visibility levels now all matter:

  • public: anyone.
  • protected: the class and its descendants. That's why the examples above used protected for $name and $priceCents: the child's downloadLink() reads $this->name.
  • private: only the declaring class. A child can't see the parent's private members, even though they exist inside the object.
PHP private members are invisible to children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

describe() reaches $owner directly because it's protected, and reaches the private $balance only through the public method balance(). Inside SavingsAccount, $this->balance refers to a property the child can't see, so isset() is false.

Prefer private, open up deliberately. Every protected member is part of your class's contract with all future subclasses, and changing it can break them. Start with private and make something protected only when a child truly needs it, or expose a protected method instead of a property.

Constructors and inheritance

Constructors are inherited like other methods:

  • If the child doesn't declare a constructor, the parent's constructor is used, with the same parameters.
  • If the child does declare one, the parent's constructor is not called automatically. You must call parent::__construct(...) yourself, usually as the first line.

Unlike other methods, a constructor's signature may be completely different from the parent's:

PHP Calling the parent constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Calling parent::__construct() matters for more than convenience: the parent's validation runs only if you call it. Forget the call, and GiftCard would skip the price check and leave $name and $priceCents uninitialized.

Signature rules for overriding

PHP checks that every override is compatible with the method it replaces, so that code written for the parent keeps working with the child. When a rule is broken, PHP stops at compile time with a fatal error. The rules:

Part of the method What the child may do
Visibility Keep it or make it wider (protected โ†’ public), never narrower
Parameters Accept the same types or wider ones (contravariance); add new parameters only if they're optional
Return type Return the same type or a narrower one (covariance), e.g. Product โ†’ DigitalProduct
static / non-static Must match

Here's what a violation looks like:

PHP
class Shape
{
    public function area(): float
    {
        return 0.0;
    }
}

class Circle extends Shape
{
    public function area(): string     // string is not compatible with float
    {
        return 'big';
    }
}
// Fatal error: Declaration of Circle::area(): string must be compatible
// with Shape::area(): float

And a valid override that uses the freedom the rules allow:

PHP Wider parameters, narrower returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The full theory behind these rules is in The PHP Type System in Depth.

Inheritance shapes: multilevel and hierarchical

PHP has single inheritance: a class extends exactly one parent. That still allows two common shapes. In multilevel inheritance a chain of classes each extends the previous one. In hierarchical inheritance several classes extend the same parent. (Reusing code from several sources is the job of traits and interfaces, not of multiple parents.)

PHP Multilevel and hierarchical inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

parent:: always reaches the direct parent, and that parent's own parent:: call continues up the chain, which is why ElectricCar prints all three sentences. Deep chains get hard to follow; if a hierarchy goes beyond two or three levels, consider composition instead.

final

Sometimes you don't want a method or class to be changed by subclasses. final forbids it:

PHP
class Payment
{
    final public function process(): void      // can't be overridden
    {
        $this->validate();
        $this->charge();
    }
    // ...
}

final class Money                            // can't be extended at all
{
    // ...
}

class FreeMoney extends Money {}
// Fatal error: Class FreeMoney cannot extend final class Money

Overriding a final method gives "Cannot override final method Payment::process()". Since PHP 8.1, class constants can be final too.

Making classes final by default is a popular modern practice, especially for value objects and services: it keeps your options open (you can remove final later without breaking anyone, but you can't add it once others extend your class). Libraries that want controlled extension points expose interfaces instead.

#[\Override] (PHP 8.3)

A subtle bug in inheritance is the override that silently stops overriding. Rename a method in the parent, or make a typo in the child, and the child's method becomes a brand-new method that nothing calls. PHP 8.3 added the #[\Override] attribute to catch this. Put it on a method that's meant to override, and PHP checks at compile time that a matching parent (or interface) method exists:

PHP Override catches a typo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This example fails on purpose. Before any line runs, PHP reports "Fatal error: EmailNotifier::sned() has #[\Override] attribute, but no matching parent method exists". Fix the typo to send and the script prints the SMS line. Without the attribute, the typo would go unnoticed and every EmailNotifier would quietly use the default send(). Attributes covers the #[...] syntax in detail.

The Liskov substitution principle

PHP's signature rules guarantee that a child's methods can be called like the parent's. They can't guarantee that the child behaves like the parent. That's the job of the Liskov substitution principle (LSP), the "L" in SOLID: code that works with a parent class must keep working when given any child.

The classic violation is a square that inherits from a rectangle:

PHP A subclass that breaks expectations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Mathematically a square is a rectangle, but this Square isn't a substitutable Rectangle: stretch() relies on width and height changing independently, and gets 16 instead of 20. Every method compiles; the bug is in the design. Fixes include making shapes immutable (no setters), or giving both classes a shared interface with only area() instead of an inheritance link.

Signs that inheritance is the wrong tool:

  • The child overrides a method to throw "not supported" or to do nothing.
  • You find yourself checking instanceof to decide what a parent-typed object can do.
  • The relationship is "has a" or "uses a" rather than "is a". A Car has an Engine, so it should hold one in a property (composition), not extend it.

Keep hierarchies shallow, one or two levels. When in doubt, prefer composition; OOP Design Principles shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Class Child extends Base and declares its own __construct() without calling parent::__construct(). What happens to Base constructor logic?

    A child constructor replaces the parent's. Call parent::__construct(...) explicitly when you need the parent's initialization and validation.
  2. 2. Base has protected function price(): int. Which override in a child class is allowed?

    Visibility may become wider (protected to public), never narrower. A different return type or a new required parameter breaks compatibility.
  3. 3. Base::total() calls $this->tax(). Child overrides tax(). What does (new Child())->total() use?

    Method calls on $this are resolved by the object's actual class, so the child's override runs. That's polymorphism.
  4. 4. What does the #[\Override] attribute do?

    Added in PHP 8.3, it turns a silent mistake (a typo or a renamed parent method) into a compile-time error.
  5. 5. Which design most clearly violates the Liskov substitution principle?

    Code written for the parent expects save() to work. A child that refuses breaks callers even though the signature is compatible.

Summary

  • class Child extends Parent inherits all public and protected members. A child object is also an instance of the parent (instanceof), and PHP allows only one parent per class.
  • Override a method by redeclaring it; call the parent's version with parent::method(). Calls on $this run the object's own override (polymorphism).
  • protected members are visible to children; private members are not, even though they exist in the object.
  • A child without a constructor inherits the parent's. A child with one must call parent::__construct(...) itself.
  • Overrides must be compatible: same or wider visibility, same or wider parameter types, optional extra parameters only, same or narrower return type.
  • final blocks overriding a method or extending a class. #[\Override] (PHP 8.3) makes PHP verify that a method really overrides something.
  • Follow the Liskov principle: a child must work wherever its parent does. When the relationship isn't truly "is a", use composition.

Next: Abstract Classes and Interfaces