Inheritance, interfaces and traits

Intermediate

Introduction

Real things come in families. A square is a kind of rectangle, and rectangles and circles are both shapes. OOP lets you describe such relations so that you can reuse code and treat different objects in the same way. PHP offers three tools for this: inheritance (a class extends another class), interfaces (a promise about which methods a class has) and traits (a block of methods you can paste into many classes). Knowing when to use each one is the heart of good design.

How it works

With extends, a child class receives the properties and methods of its parent class. The child can add new members and override old ones by writing a method with the same name. Inside the child, parent::method() calls the parent's version, and parent::__construct(...) runs the parent's constructor. A class can have only one parent.

An abstract class is a class that cannot be created with new. It can contain finished methods and abstract methods, which have no body and must be written by the children. It is the right tool when the children share code and a base idea.

An interface lists methods without bodies. A class says implements Shape and must provide every method of the interface. A class may implement many interfaces. The interface is a contract: any code that asks for a Shape can call area() without caring which class the object comes from.

This is polymorphism: the same call does different things depending on the real object. A loop over an array of shapes calls describe() on each one, and every shape answers in its own way. The check $s instanceof Rect asks whether an object belongs to a class or any of its children. A square is a rect, so the answer is true. A type declaration such as Shape $s accepts any object of a class that implements the interface.

A trait solves another problem. Because a class has only one parent, you cannot inherit code from two places. A trait holds methods that you add to a class with use Describes;. The trait method can call other methods of the class, and static::class gives the real class name of the object. Use traits for shared helper behaviour such as logging, and not as a replacement for a real parent class.

The protected visibility lets children use a member that the outside cannot. Prefer to build with small classes and interfaces, and use inheritance only when the sentence "a child is a kind of parent" is true. A square is a kind of rectangle, but a car is not a kind of engine; a car has an engine.

Example

<?php
interface Shape
{
    public function area(): float;
}

trait Describes
{
    public function describe(): string
    {
        return static::class . " with area " . number_format($this->area(), 2);
    }
}

abstract class Base implements Shape
{
    use Describes;

    public function __construct(protected string $label)
    {
    }

    public function label(): string
    {
        return $this->label;
    }
}

class Rect extends Base
{
    public function __construct(protected float $w, protected float $h)
    {
        parent::__construct("rectangle");
    }

    public function area(): float
    {
        return $this->w * $this->h;
    }
}

class Square extends Rect
{
    public function __construct(float $side)
    {
        parent::__construct($side, $side);
        $this->label = "square";
    }
}

class Circle extends Base
{
    public function __construct(private float $r)
    {
        parent::__construct("circle");
    }

    public function area(): float
    {
        return round(3.14159 * $this->r * $this->r, 2);
    }
}

$shapes = [new Rect(3, 4), new Square(5), new Circle(2)];
foreach ($shapes as $s) {
    echo $s->label(), ": ", $s->describe(), "\n";
}
echo $shapes[1] instanceof Rect ? "a square is a rect" : "no", "\n";
echo $shapes[2] instanceof Shape ? "a circle is a Shape" : "no", "\n";
echo array_sum(array_map(fn(Shape $s) => $s->area(), $shapes)), "\n";

Line by line

  1. The interface Shape promises an area() method.
  2. The trait Describes has a describe() method that uses area() and the real class name.
  3. The abstract class Base implements Shape, uses the trait and keeps a protected label.
  4. Rect extends Base, calls the parent constructor and writes area().
  5. Square extends Rect and changes the label after calling the parent constructor.
  6. Circle extends Base with its own area().
  7. A loop over three different objects calls the same methods on each.
  8. instanceof shows that a square is a Rect and a circle is a Shape, and array_map adds up the areas.

Expected result

rectangle: Rect with area 12.00
square: Square with area 25.00
circle: Circle with area 12.57
a square is a rect
a circle is a Shape
49.57

In the real world

Frameworks use interfaces for everything that can be replaced: a logger interface can send messages to a file, a screen or a service, and the rest of the code does not change. Payment systems have one interface and one class for each payment method. Traits are used for shared small features, and abstract classes give a base to controllers, models and commands.

Common mistakes

  • Using inheritance when "has a" is true. A car has an engine; it is not one.
  • Forgetting to implement every method of an interface, which is a fatal error.
  • Trying to create an object of an abstract class.
  • Forgetting parent::__construct(...), so the parent's properties stay empty.

Best practices

  • Program against interfaces, not against one concrete class.
  • Keep inheritance chains short.
  • Mark methods and classes final when they should not be extended.
  • Use traits for small, shared behaviour only.

Summary

extends makes a child class that reuses and overrides the parent's code, and abstract forces the children to finish it. An interface is a contract of methods, and one class may implement many. Polymorphism lets one call work on many kinds of objects. A trait adds shared methods to unrelated classes.

Quick check

1. How many parent classes can a PHP class have?
2. What must a class do when it implements an interface?
3. What is polymorphism?
4. Which tool adds the same methods to unrelated classes?

Key takeaways

  • extends builds a child class and abstract forces children to finish the code.
  • An interface is a contract; one class can implement many.
  • A trait shares methods between unrelated classes.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.