PHPのインターフェースは、クラスが持つと約束するメソッドを並べたものです:interface Shape { public function area(): float; }とし、class Circle implements Shapeはarea()を定義しなければなりません。インターフェースによる型宣言、複数のインターフェースの実装、インターフェースの定数、インターフェースの継承、Countableなどの組み込みインターフェース、インターフェースと抽象クラスの違いを学びます。
PHPのインターフェースは、クラスが提供すると約束するメソッドを、コードなしで宣言します:interface Shape { public function area(): float; }。implements Shapeと書いたクラスはarea()を定義しなければならず、Shapeで型宣言した関数はどれもそのクラスを受け付けます。
<?php
interface Shape
{
public function area(): float;
}
class Square implements Shape
{
public function __construct(private float $side) {}
public function area(): float
{
return $this->side ** 2;
}
}
class Circle implements Shape
{
public function __construct(private float $r) {}
public function area(): float
{
return round(M_PI * $this->r ** 2, 2);
}
}
function describe(Shape $s): string
{
return get_class($s) . ' with area ' . $s->area();
}
echo describe(new Square(3)), "\n";
echo describe(new Circle(2)), "\n";
var_dump(new Circle(1) instanceof Shape);
<?php
interface Notifier
{
public function send(string $to, string $message): bool;
}
class EmailNotifier implements Notifier
{
public function send(string $to, string $message): bool
{
echo "Email to $to: $message\n";
return true;
}
}
class FakeNotifier implements Notifier
{
public array $sent = [];
public function send(string $to, string $message): bool
{
$this->sent[] = [$to, $message];
return true;
}
}
class OrderService
{
public function __construct(private Notifier $notifier) {}
public function place(string $customer, int $orderId): void
{
$this->notifier->send($customer, "Order #$orderId confirmed");
}
}
(new OrderService(new EmailNotifier()))->place('ada@example.com', 1001);
$fake = new FakeNotifier();
(new OrderService($fake))->place('linus@example.com', 1002);
print_r($fake->sent);
<?php
// This fails on purpose: Invoice does not define total()
interface Billable
{
public function total(): float;
public function currency(): string;
}
class Invoice implements Billable
{
public function currency(): string
{
return 'EUR';
}
}
echo (new Invoice())->currency();
本体のないpublicなメソッドのシグネチャの一覧です:interface Logger { public function log(string $msg): void; }。implements Loggerと書いたクラスはその中のメソッドをすべて定義しなければならず、Loggerで型宣言したコードはどれもそのクラスを受け付けます。