当前位置:首页 > PHP

php实现接口

2026-02-13 13:18:54PHP

PHP 实现接口的方法

定义接口

接口使用 interface 关键字定义,可以包含方法声明但不包含实现。所有方法默认为公共方法。

interface PaymentGateway {
    public function processPayment($amount);
    public function refundPayment($transactionId);
}

实现接口

类使用 implements 关键字实现接口,必须提供接口中所有方法的具体实现。

php实现接口

class StripePayment implements PaymentGateway {
    public function processPayment($amount) {
        // Stripe 支付处理逻辑
        return "Processed payment of $amount via Stripe";
    }

    public function refundPayment($transactionId) {
        // Stripe 退款处理逻辑
        return "Refunded transaction $transactionId via Stripe";
    }
}

多接口实现

一个类可以实现多个接口,用逗号分隔。

interface Logger {
    public function log($message);
}

class PayPalPayment implements PaymentGateway, Logger {
    public function processPayment($amount) {
        // PayPal 支付处理逻辑
        return "Processed payment of $amount via PayPal";
    }

    public function refundPayment($transactionId) {
        // PayPal 退款处理逻辑
        return "Refunded transaction $transactionId via PayPal";
    }

    public function log($message) {
        // 日志记录逻辑
        echo "Log: $message";
    }
}

接口继承

接口可以继承其他接口,扩展功能。

php实现接口

interface AdvancedPaymentGateway extends PaymentGateway {
    public function authorize($credentials);
}

class SquarePayment implements AdvancedPaymentGateway {
    public function processPayment($amount) {
        // Square 支付处理逻辑
    }

    public function refundPayment($transactionId) {
        // Square 退款处理逻辑
    }

    public function authorize($credentials) {
        // Square 授权逻辑
    }
}

类型提示

接口可用于类型提示,确保参数实现特定接口。

function handlePayment(PaymentGateway $gateway, $amount) {
    echo $gateway->processPayment($amount);
}

$stripe = new StripePayment();
handlePayment($stripe, 100.00);

常量定义

接口可以包含常量,实现类不能覆盖这些常量。

interface Shipping {
    const DEFAULT_COUNTRY = 'US';

    public function calculateShipping($address);
}

class FedExShipping implements Shipping {
    public function calculateShipping($address) {
        // 使用接口常量
        if ($address['country'] === Shipping::DEFAULT_COUNTRY) {
            return 5.00;
        }
        return 15.00;
    }
}

实际应用示例

REST API 接口实现

interface ApiEndpoint {
    public function handleRequest($requestData);
}

class UserEndpoint implements ApiEndpoint {
    public function handleRequest($requestData) {
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                return $this->getUser($requestData['id']);
            case 'POST':
                return $this->createUser($requestData);
            default:
                throw new Exception('Method not allowed');
        }
    }

    private function getUser($id) {
        // 获取用户逻辑
    }

    private function createUser($data) {
        // 创建用户逻辑
    }
}

// 使用示例
$endpoint = new UserEndpoint();
try {
    $response = $endpoint->handleRequest($_REQUEST);
    echo json_encode($response);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

数据库访问接口

interface DatabaseAdapter {
    public function connect($config);
    public function query($sql);
    public function close();
}

class MySQLAdapter implements DatabaseAdapter {
    private $connection;

    public function connect($config) {
        $this->connection = new mysqli(
            $config['host'],
            $config['user'],
            $config['password'],
            $config['database']
        );
    }

    public function query($sql) {
        return $this->connection->query($sql);
    }

    public function close() {
        $this->connection->close();
    }
}

注意事项

  • 接口方法必须被实现类全部实现,否则会触发致命错误
  • 接口不能包含属性,只能包含方法和常量
  • 实现接口时方法签名必须完全匹配(参数数量和类型)
  • PHP 8.0 开始支持接口中的静态方法
  • 接口可以用于实现多继承效果,因为类可以实现多个接口

标签: 接口php
分享给朋友:

相关文章

vue调用接口实现退出

vue调用接口实现退出

Vue 调用接口实现退出功能 在 Vue 中实现退出功能通常需要调用后端接口,清除用户登录状态,并跳转到登录页面或其他指定页面。以下是实现步骤: 定义退出接口方法 在 Vue 项目中,通常会在 s…

php实现表单

php实现表单

PHP 表单基础实现 创建一个简单的 PHP 表单需要 HTML 表单结构和 PHP 处理脚本。以下是一个完整的示例: HTML 表单部分 (form.html) <form action=…

php购物车实现

php购物车实现

PHP购物车实现方法 使用PHP实现购物车功能可以通过多种方式完成,以下是几种常见的实现方法: Session存储购物车数据 利用PHP的$_SESSION超全局变量存储购物车数据是最简单的方法。…

php实现排序

php实现排序

PHP 数组排序方法 PHP 提供了多种内置函数用于数组排序,适用于不同的排序需求。以下是常见的排序方法: 按值升序排序 sort() 函数对数组按值升序排序,重置键名(索引数组适用): $n…

基于php的设计与实现

基于php的设计与实现

PHP 设计与实现的关键要素 环境搭建与框架选择 PHP开发需配置服务器环境(如Apache/Nginx)、PHP版本(建议7.4+)及数据库(MySQL/MariaDB)。主流框架包括Laravel…

php实现的分页

php实现的分页

PHP 实现分页的方法 基本分页逻辑 分页的核心在于计算总页数、当前页码以及数据偏移量。假设每页显示 10 条数据: $current_page = isset($_GET['page']) ? (…