CodeBlanks Logo Icon CodeBlanks

Defining interfaces

PHP course · Intermediate · Lesson 47/115

Learn to define a contract with the interface keyword.

The interface keyword

An interface is a contract that lists the methods a class must implement. It looks like a class but holds no state (no properties); it lists only public method signatures and constants.

A method signature declares the method name and parameters but has no body { }; it ends with a semicolon. Every class that implements the interface must write these methods with its own body.

This way different classes follow the same contract and can replace each other. This is the foundation of polymorphism.

Interface syntax

An interface declaration starts with the interface keyword followed by a name: interface Shape { ... }. Method signatures go inside the braces.

Each signature looks like public function area(): float;; no body, ending with a semicolon. Even without public, methods are implicitly public.

An interface may also declare constants like const VERSION = '1.0';. But it cannot declare properties like $name; an interface holds no state.

Test yourself

  1. What describes an interface?

    • Method definitions together with method bodies
    • Method signatures listed without bodies
    • Holds properties and a constructor
    • Is instantiated directly with new
    Show answer

    Method signatures listed without bodies — Correct. An interface lists only method signatures without bodies; it has no body or properties.

  2. Write a method signature in an interface

    interface Shape {
        ____
    }
    Show answer
    interface Shape {
        public function area(): float;
    }
  3. Match the interface terms

    interface
    Contract
    method signature
    Bodyless declaration
    public function
    Default access
    semicolon
    Signature end
  4. Which is NOT found in an interface?

    • method signature
    • class constant (const)
    • property ($name)
    • public method
    Show answer

    property ($name) — Correct. An interface cannot hold properties; it contains only signatures and constants.

All lessons in Intermediate