实现interface php
在PHP中实现接口
PHP中使用interface关键字定义接口,通过implements关键字实现接口。接口定义方法签名,实现类需提供具体实现。
定义接口
interface MyInterface {
public function method1();
public function method2($param);
}
实现接口
class MyClass implements MyInterface {
public function method1() {
echo "Implementation of method1";
}
public function method2($param) {
echo "Implementation of method2 with param: " . $param;
}
}
多接口实现
PHP支持一个类实现多个接口:
interface InterfaceA {
public function methodA();
}
interface InterfaceB {
public function methodB();
}
class MyClass implements InterfaceA, InterfaceB {
public function methodA() {
echo "Method A";
}
public function methodB() {
echo "Method B";
}
}
接口继承
接口可以继承其他接口:
interface InterfaceA {
public function methodA();
}
interface InterfaceB extends InterfaceA {
public function methodB();
}
class MyClass implements InterfaceB {
public function methodA() {
echo "Method A";
}
public function methodB() {
echo "Method B";
}
}
抽象类实现部分接口
抽象类可以实现接口的部分方法:
interface MyInterface {
public function method1();
public function method2();
}
abstract class MyAbstractClass implements MyInterface {
public function method1() {
echo "Implemented method1";
}
// method2 remains abstract
}
class ConcreteClass extends MyAbstractClass {
public function method2() {
echo "Implemented method2";
}
}
类型提示中使用接口
接口可用于类型提示:
function process(MyInterface $obj) {
$obj->method1();
$obj->method2("test");
}
$obj = new MyClass();
process($obj);
常量接口
接口可以包含常量:

interface Constants {
const PI = 3.14;
const VERSION = "1.0";
}
echo Constants::PI; // 输出 3.14






