php 实现接口
PHP 实现接口的基本方法
在 PHP 中,接口(Interface)用于定义一组方法的规范,而不实现具体逻辑。类通过实现接口来遵循这些规范。
定义接口语法:
interface InterfaceName {
public function method1();
public function method2($param);
}
实现接口语法:
class ClassName implements InterfaceName {
public function method1() {
// 具体实现
}
public function method2($param) {
// 具体实现
}
}
多个接口的实现
一个类可以同时实现多个接口,用逗号分隔接口名称。

interface InterfaceA {
public function methodA();
}
interface InterfaceB {
public function methodB();
}
class MyClass implements InterfaceA, InterfaceB {
public function methodA() {
// 实现 methodA
}
public function methodB() {
// 实现 methodB
}
}
接口继承
接口可以继承其他接口,扩展方法定义。
interface ParentInterface {
public function parentMethod();
}
interface ChildInterface extends ParentInterface {
public function childMethod();
}
class MyClass implements ChildInterface {
public function parentMethod() {
// 实现 parentMethod
}
public function childMethod() {
// 实现 childMethod
}
}
实际应用示例
定义支付接口:

interface PaymentGateway {
public function processPayment($amount);
public function verifyPayment($transactionId);
}
实现支付接口:
class PayPal implements PaymentGateway {
public function processPayment($amount) {
// PayPal 支付处理逻辑
echo "Processing PayPal payment for $amount";
}
public function verifyPayment($transactionId) {
// PayPal 支付验证逻辑
echo "Verifying PayPal transaction $transactionId";
}
}
class Stripe implements PaymentGateway {
public function processPayment($amount) {
// Stripe 支付处理逻辑
echo "Processing Stripe payment for $amount";
}
public function verifyPayment($transactionId) {
// Stripe 支付验证逻辑
echo "Verifying Stripe transaction $transactionId";
}
}
类型提示与接口
可以在函数参数中使用接口作为类型提示,确保传入的对象实现了特定接口。
function handlePayment(PaymentGateway $gateway, $amount) {
$gateway->processPayment($amount);
// 其他处理逻辑
}
$paypal = new PayPal();
handlePayment($paypal, 100);
接口与抽象类的区别
- 接口只能包含方法声明,不能包含属性或方法实现
- 类可以实现多个接口,但只能继承一个抽象类
- 接口所有方法都是公开的,抽象类可以有各种可见性的方法
- 接口不能有构造函数,抽象类可以有
最佳实践
- 使用接口定义行为规范,而不是具体实现
- 保持接口小巧专注(单一职责原则)
- 为接口使用描述性名称,通常以"-able"结尾(如 Loggable, Cacheable)
- 在需要多态行为时优先考虑接口而非继承
PHP 8.0 接口新特性
PHP 8.0 开始,接口可以包含具体方法实现(通过 default 方法):
interface Logger {
public function log($message);
public function logError($error) {
$this->log("[ERROR] " . $error);
}
}
实现该接口的类可以直接使用 logError 方法,也可以覆盖它。






