php实现对象接口
PHP 实现对象接口的方法
在 PHP 中,接口(Interface)用于定义一组方法的规范,类可以通过实现接口来遵循这些规范。接口的核心作用是实现多态性和代码解耦。
定义接口
接口通过 interface 关键字定义,方法不包含具体实现:
interface LoggerInterface {
public function log($message);
}
实现接口
类使用 implements 关键字实现接口,必须实现接口中所有方法:

class FileLogger implements LoggerInterface {
public function log($message) {
file_put_contents('log.txt', $message, FILE_APPEND);
}
}
多接口实现
一个类可以实现多个接口:
interface NotifierInterface {
public function notify($recipient);
}
class EmailNotifier implements LoggerInterface, NotifierInterface {
public function log($message) {
// 日志实现
}
public function notify($recipient) {
// 通知实现
}
}
接口继承
接口可以继承其他接口:

interface AdvancedLoggerInterface extends LoggerInterface {
public function logWithTimestamp($message);
}
类型检查
通过类型提示检查对象是否实现接口:
function process(LoggerInterface $logger) {
$logger->log('Processing started');
}
实际应用示例
interface PaymentGateway {
public function charge($amount);
}
class StripePayment implements PaymentGateway {
public function charge($amount) {
echo "Charging $amount via Stripe";
}
}
class PayPalPayment implements PaymentGateway {
public function charge($amount) {
echo "Charging $amount via PayPal";
}
}
function processPayment(PaymentGateway $gateway, $amount) {
$gateway->charge($amount);
}
$stripe = new StripePayment();
processPayment($stripe, 100); // 输出: Charging 100 via Stripe
关键点:
- 接口方法必须是 public
- 实现类必须实现接口所有方法
- 接口不能包含属性
- 接口可以定义常量
- PHP 8.0 后接口可以定义静态方法






