Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 147 ยท Object-Oriented PHP

Abstract Classes and Interfaces

Learn PHP abstract classes and methods, interfaces, implementing several interfaces, interface constants, Stringable, Countable and how to choose.

Inheritance lets a child class reuse a parent's code. But sometimes the parent can't sensibly do the job itself. What's the area of a generic "shape"? How does a generic "payment" charge a card? You want the parent to say every subclass must be able to do this without providing the answer. And sometimes you want a guarantee that has nothing to do with shared code at all: "this object can be logged", "this object can be counted", no matter what class it is.

PHP has two tools for this. An abstract class is a partly finished class: it can hold real code and properties, but it leaves some methods for children to complete, and it can't be instantiated itself. An interface is a pure contract: a list of public methods a class promises to provide, with no code at all. A class can extend only one class but implement any number of interfaces.

This lesson covers both, plus interface constants, two built-in interfaces you'll use constantly (Stringable and Countable), and a practical guide to choosing between them.

Abstract classes

Mark a class abstract and it becomes a template rather than something you can create. Inside it, an abstract method declares a signature with no body, ending in a semicolon. Every concrete (non-abstract) child must implement all of them:

PHP An abstract base class

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() is written once, in the abstract class, and calls area() without knowing how any specific shape computes it. Each child fills in only the part that differs. Trying to create a plain Shape throws "Cannot instantiate abstract class Shape".

The rules:

  • A class with even one abstract method must itself be declared abstract.
  • An abstract class can have everything a normal class has: properties, constructors, concrete methods, constants. It can also have zero abstract methods, if you simply want to forbid creating it directly.
  • A child that doesn't implement every abstract method must be abstract too. Otherwise PHP stops at compile time:
PHP
class Triangle extends Shape
{
    // forgot area()
}
// Fatal error: Class Triangle contains 1 abstract method and must therefore be
// declared abstract or implement the remaining method (Shape::area)
  • The implementation must follow the signature rules for overriding: compatible parameter and return types, same or wider visibility.

The template method pattern

The describe()/area() split is an example of a well-known design called the template method pattern: the abstract class fixes the overall algorithm (often in a final method) and children supply individual steps. Here it is in a more realistic form, a report exporter:

PHP Template method: fixed steps, custom details

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 abstract steps are protected: outside code calls only export(), and the steps are implementation details for subclasses. footer() is a concrete method children may override, which is called a hook.

Interfaces

An interface declares what an object can do, without saying how and without any shared code. It's written with the interface keyword and contains public method signatures (and optionally constants). A class promises to fulfil it with implements:

PHP Defining and implementing an interface

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.

OrderService depends only on the Notifier interface. It doesn't know or care whether messages go by email, SMS, or (in a test) into an array. Swapping implementations needs no change to OrderService. That's the main reason interfaces exist: they let parts of a program depend on capabilities instead of concrete classes, which is the heart of dependency injection and testable design.

Interface rules:

  • All interface methods are public, and they have no body.
  • An interface can't be instantiated: new Notifier() throws "Cannot instantiate interface Notifier".
  • Interfaces can't declare ordinary properties. Since PHP 8.4, they can declare properties with hooks (public string $name { get; }), covered in Property Hooks.
  • A class must implement every method of every interface it lists, with compatible signatures, or be declared abstract.

Implementing several interfaces

A class can implement any number of interfaces, separated by commas, and can extend a class at the same time. Interfaces can also extend other interfaces, even several at once:

PHP Multiple interfaces and interface 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.

User gets id() from its parent Model, and that inherited method counts toward implementing HasId. JsonSerializable is a built-in interface: json_encode() calls jsonSerialize() on any object that implements it (more in JSON). class_implements() lists every interface an object's class implements, including inherited ones. ::class gives a class or interface name as a string.

Interface constants

Interfaces can hold constants, which every implementing class inherits:

PHP
interface Cache
{
    public const int DEFAULT_TTL = 3600;     // typed constant: PHP 8.3

    public function set(string $key, mixed $value, int $ttl = self::DEFAULT_TTL): void;
}

class MemoryCache implements Cache
{
    // ...
}

echo MemoryCache::DEFAULT_TTL;   // 3600
echo Cache::DEFAULT_TTL;         // 3600

Since PHP 8.1, an implementing class may override an interface constant unless the interface marks it final. Constants work well for values that are part of the contract, like a default timeout or a version number. For a fixed set of options ("pending", "paid", "shipped"), use an enum instead of a group of constants.

Built-in interfaces: Stringable and Countable

PHP ships with many interfaces that hook your objects into the language itself. Two are especially common.

Stringable (PHP 8.0) means "this object can be converted to a string". Any class that defines a __toString() magic method implements it automatically, even without writing implements Stringable. Use it as a type when a function accepts strings or string-like objects.

Countable means "count() works on this object". It has one method, count(): int. Without it, passing an object to count() throws a TypeError.

PHP Stringable and Countable

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.

Other built-in interfaces you'll meet: Iterator and IteratorAggregate (make objects work in foreach) and ArrayAccess (allow $obj['key']), all covered in Iterators and the SPL; JsonSerializable; and Throwable, which every exception implements (Exceptions).

Abstract class or interface?

They overlap, so here's how they differ:

Abstract class Interface
Can contain code Yes: properties, constructors, concrete methods No method bodies (only constants, and 8.4 property hooks declarations)
How many per class One (extends) Any number (implements A, B, C)
Visibility of members Any Methods are always public
Can be instantiated No No
Expresses "is a kind of" with shared implementation "can do" / a capability or role
Changing it later Adding a concrete method is safe Adding a method breaks every implementer

Practical guidelines:

  • Type your parameters with interfaces. function __construct(Notifier $notifier) accepts any implementation, including test fakes. That's the most valuable use of interfaces.
  • Use an abstract class to share code between closely related classes that genuinely are variations of one thing, like the shapes or the exporters above.
  • Combine them. A common pattern is an interface for the contract plus an abstract base class that implements it partially, for convenience: abstract class AbstractNotifier implements Notifier. Callers type against the interface; implementers may extend the base class or start from scratch.
  • Keep interfaces small. An interface with one or two methods (Countable, Stringable, Notifier) is easy to implement and to fake. That's the interface segregation principle from SOLID.

For sharing code across classes that don't belong in one hierarchy, there's a third tool: traits, the topic of the next lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens on new Shape() when Shape is declared abstract class Shape?

    An abstract class can never be instantiated, even if it has no abstract methods. You create objects of concrete child classes instead.
  2. 2. Which statement about interfaces is true?

    class User extends Model implements Entity, JsonSerializable is valid. Interface methods are always public and have no bodies.
  3. 3. A class defines __toString() but doesn't write "implements Stringable". What does $obj instanceof Stringable return?

    Since PHP 8.0, every class with __toString() implements Stringable automatically.
  4. 4. What does count($obj) do when $obj does not implement Countable?

    In PHP 8, count() accepts only arrays and Countable objects. Anything else throws a TypeError such as: count(): Argument #1 ($value) must be of type Countable|array, Tag given.
  5. 5. You want OrderService to work with email, SMS and a fake notifier in tests. What should its constructor parameter type be?

    Depending on an interface lets you swap implementations freely while still getting type checks.

Summary

  • An abstract class can't be instantiated. It may hold properties, constructors and concrete methods, plus abstract methods (signature only) that every concrete child must implement.
  • The template method pattern puts the fixed algorithm in the abstract class and lets children supply the steps.
  • An interface lists public method signatures (and constants) with no code. Classes promise to fulfil it with implements; a class can implement many interfaces, and interfaces can extend several others.
  • Type parameters with interfaces so implementations can be swapped, including fakes in tests.
  • Interface constants are inherited by implementers; since PHP 8.1 they can be overridden unless final.
  • Stringable is implemented automatically by any class with __toString(). Countable makes count($obj) work; without it count() throws a TypeError.
  • Choose an abstract class to share code within one family, an interface to describe a capability; combine them when useful.

Next: Traits