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.
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.
<?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();
?>16Square implements the Shape interface by providing its own area() method.
<?php
trait Greetable {
function greet() {
return "Hello from " . get_class($this);
}
}
class User {
use Greetable;
}
echo (new User())->greet();
?>Hello from UserThe 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.
