PHP Tutorial · Object-Oriented PHP · Lesson 32 of 38
PHP Interfaces and Abstract Classes
Define contracts with interfaces and share code with abstract classes.
Interfaces
An interface lists methods a class promises to implement. Code that depends on the interface works with any implementation — the key to swappable, testable code:
<?php
interface Cache
{
public function get(string $key): ?string;
public function set(string $key, string $value): void;
}
final class ArrayCache implements Cache
{
private array $items = [];
public function get(string $key): ?string
{
return $this->items[$key] ?? null;
}
public function set(string $key, string $value): void
{
$this->items[$key] = $value;
}
}
function cachedGreeting(Cache $cache, string $name): string
{
$key = "greet:$name";
if ($hit = $cache->get($key)) {
return "$hit (from cache)";
}
$value = "Hello, $name!";
$cache->set($key, $value);
return $value;
}
$cache = new ArrayCache();
echo cachedGreeting($cache, "Ada"), "\n";
echo cachedGreeting($cache, "Ada"), "\n";
Output
Hello, Ada! Hello, Ada! (from cache)
Abstract classes
An abstract class can't be instantiated. It can contain real methods and abstract methods that children must implement:
<?php
abstract class Shape
{
abstract public function area(): float;
public function describe(): string
{
return sprintf("%s with area %.2f", static::class, $this->area());
}
}
class Circle extends Shape
{
public function __construct(private float $r) {}
public function area(): float { return M_PI * $this->r ** 2; }
}
class Rectangle extends Shape
{
public function __construct(private float $w, private float $h) {}
public function area(): float { return $this->w * $this->h; }
}
foreach ([new Circle(1), new Rectangle(2, 3)] as $shape) {
echo $shape->describe(), "\n";
}
Output
Circle with area 3.14 Rectangle with area 6.00
Rule of thumb: use an interface to describe what something can do; use an abstract class to share how similar classes do it. A class can implement many interfaces but extend only one class.
Test yourself
How many interfaces can a PHP class implement?
OneTwoAny numberNone
Show answer
Answer: Any number