PHP ยท Chapter 38 of 44

PHP Interfaces & Traits

An interface defines a contract of method names that implementing classes must provide, without specifying how those methods work. This ensures different classes share a consistent set of capabilities, even if unrelated by inheritance.

A trait is a mechanism for reusing method implementations across multiple unrelated classes, solving PHP's lack of multiple inheritance. A class can use multiple traits at once with the use keyword.

Syntax
interface Shape {
  function area();
}
trait Logger {
  function log($msg) { }
}
class Circle implements Shape {
  use Logger;
}

Defining and implementing interfaces

interface Shape { function area(); } declares a method signature. A class uses implements Shape to promise it will define that method.

Using traits

trait Greetable { function greet() { return "Hi!"; } } defines reusable code that any class can pull in with use Greetable; inside its body.

Example 1 (php)
<?php
  interface Shape {
    function area();
  }
  class Square implements Shape {
    public $side;
    function __construct($side) { $this->side = $side; }
    function area() { return $this->side * $this->side; }
  }
  $s = new Square(4);
  echo $s->area();
?>
Output
16

Square implements the Shape interface by providing its own area() method.

Example 2 (php)
<?php
  trait Greetable {
    function greet() {
      return "Hello from " . get_class($this);
    }
  }
  class User {
    use Greetable;
  }
  echo (new User())->greet();
?>
Output
Hello from User

The trait's greet() method becomes available on User just as if it were written directly in the class.

Key points

  • An interface defines method signatures a class must implement.
  • A class uses implements to fulfill an interface's contract.
  • A trait provides reusable method implementations across classes.
  • A class can use multiple traits with the use keyword.
๐Ÿ’ก Note: Interfaces describe 'what' a class can do, while traits provide 'how' by sharing actual code.

๐Ÿ“ Quick Quiz

1. What does an interface define?

2. Which keyword lets a class use a trait?

3. Can a class implement multiple interfaces?