php 实现接口
PHP 实现接口的基本方法
在 PHP 中,接口(Interface)用于定义一组方法的规范,而不实现具体功能。类可以实现(implement)接口,并必须实现接口中定义的所有方法。
定义接口
使用 interface 关键字定义接口,接口中可以包含方法声明但不包含方法体。
interface MyInterface {
public function method1();
public function method2($param);
}
实现接口
类使用 implements 关键字实现接口,必须实现接口中定义的所有方法。

class MyClass implements MyInterface {
public function method1() {
echo "Method 1 implementation";
}
public function method2($param) {
echo "Method 2 implementation with param: " . $param;
}
}
多接口实现
一个类可以实现多个接口,用逗号分隔。
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";
}
}
接口继承
接口可以继承其他接口,使用 extends 关键字。

interface ParentInterface {
public function parentMethod();
}
interface ChildInterface extends ParentInterface {
public function childMethod();
}
class MyClass implements ChildInterface {
public function parentMethod() {
echo "Parent method";
}
public function childMethod() {
echo "Child method";
}
}
类型提示
接口可以用于类型提示,确保传入的对象实现了特定接口。
function process(MyInterface $obj) {
$obj->method1();
}
$obj = new MyClass();
process($obj);
常量定义
接口中可以定义常量,实现接口的类可以直接使用这些常量。
interface MyInterface {
const CONSTANT = 'value';
}
echo MyInterface::CONSTANT; // 输出 'value'
通过以上方法,可以在 PHP 中有效地使用接口来规范类的行为,提高代码的可维护性和扩展性。






