接口 #

一、接口基础 #

1.1 定义接口 #

php
<?php
interface LoggerInterface
{
    public function log(string $message): void;
    public function error(string $message): void;
}

1.2 实现接口 #

php
<?php
class FileLogger implements LoggerInterface
{
    public function log(string $message): void
    {
        file_put_contents('app.log', "[INFO] $message\n", FILE_APPEND);
    }
    
    public function error(string $message): void
    {
        file_put_contents('app.log', "[ERROR] $message\n", FILE_APPEND);
    }
}

1.3 多接口实现 #

php
<?php
interface Readable
{
    public function read(): string;
}

interface Writable
{
    public function write(string $data): void;
}

class FileHandler implements Readable, Writable
{
    public function read(): string
    {
        return file_get_contents('data.txt');
    }
    
    public function write(string $data): void
    {
        file_put_contents('data.txt', $data);
    }
}

二、接口特性 #

2.1 常量 #

php
<?php
interface Status
{
    public const ACTIVE = 1;
    public const INACTIVE = 0;
}

echo Status::ACTIVE;

2.2 默认方法(PHP 8.0+) #

php
<?php
interface LoggerInterface
{
    public function log(string $message): void;
    
    public function error(string $message): void
    {
        $this->log("[ERROR] $message");
    }
}

三、实际应用 #

3.1 依赖注入 #

php
<?php
class UserService
{
    public function __construct(
        private LoggerInterface $logger
    ) {}
    
    public function create(array $data): User
    {
        $this->logger->log("Creating user");
        return new User($data);
    }
}

3.2 仓储模式 #

php
<?php
interface UserRepositoryInterface
{
    public function find(int $id): ?User;
    public function save(User $user): bool;
    public function delete(int $id): bool;
}

class MySqlUserRepository implements UserRepositoryInterface
{
    public function find(int $id): ?User
    {
        
    }
    
    public function save(User $user): bool
    {
        
    }
    
    public function delete(int $id): bool
    {
        
    }
}

四、总结 #

本章学习了:

  • 接口定义
  • 接口实现
  • 多接口实现
  • 接口常量
  • 依赖注入

下一章将学习抽象类。

最后更新:2026-03-26