php怎么实现接口
实现接口的基本方法
在PHP中,接口通过interface关键字定义,类使用implements关键字实现接口。接口定义方法签名,实现类需具体实现这些方法。
interface MyInterface {
public function method1();
public function method2();
}
class MyClass implements MyInterface {
public function method1() {
// 具体实现
}
public function method2() {
// 具体实现
}
}
接口的多重实现
PHP支持一个类实现多个接口,用逗号分隔接口名。
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
}
}
类型提示与接口
接口可用于类型提示,确保参数或返回值符合特定契约。
function process(MyInterface $obj) {
$obj->method1();
}
接口常量
接口可以包含常量,实现类不能覆盖这些常量。
interface MyInterface {
const CONSTANT = 'value';
}
echo MyInterface::CONSTANT; // 输出 'value'
抽象类与接口结合
抽象类可以实现部分接口方法,剩余方法由子类实现。
interface MyInterface {
public function method1();
public function method2();
}
abstract class MyAbstractClass implements MyInterface {
public function method1() {
// 实现method1
}
// method2留给子类实现
}
class MyClass extends MyAbstractClass {
public function method2() {
// 实现method2
}
}
实际应用示例
定义支付接口,不同支付方式实现统一接口。
interface PaymentGateway {
public function processPayment($amount);
}
class PayPal implements PaymentGateway {
public function processPayment($amount) {
// PayPal支付逻辑
}
}
class Stripe implements PaymentGateway {
public function processPayment($amount) {
// Stripe支付逻辑
}
}
function checkout(PaymentGateway $gateway, $amount) {
$gateway->processPayment($amount);
}






