PHP interface 不能实例化,必须由具体类实现后才能 new;其方法仅允许 public 修饰符,禁止 final/static/protected/private;多接口同名方法参数须完全兼容。

interface 声明后不能直接 new
PHP 的 interface 是契约,不是类,不能实例化。写 new MyInterface() 会报 Fatal error: Cannot instantiate interface。这点和抽象类不同,哪怕 interface 里全是空方法,也不行。
必须用具体类 implements 它,再实例化那个类:
interface Logger {
public function log(string $msg): void;
}
class FileLogger implements Logger {
public function log(string $msg): void {
file_put_contents('app.log', $msg . PHP_EOL, FILE_APPEND);
}
}
$logger = new FileLogger(); // ✅ 正确
// $logger = new Logger(); // ❌ 致命错误
- 常见错误:把 interface 当成基类,在工厂或 DI 容器配置里直接 new interface 名字
- 正确做法:容器绑定时,把 interface 映射到具体实现类,如
$container->bind(Logger::class, FileLogger::class) - 如果只声明 interface 没写任何
implements类,代码能通过语法检查,但运行时根本没法用——这是典型的“编译通过,上线报错”陷阱
interface 方法不能有访问修饰符以外的修饰符
PHP interface 中的方法只能是 public,且不能加 final、static、abstract(它本身就是抽象的)、protected 或 private。写错会触发 Parse error: syntax error。
比如下面这些全都不合法:
立即学习“PHP免费学习笔记(深入)”;
interface Service {
final public function run(); // ❌ final 不允许
static public function init(); // ❌ static 不允许
protected function check(); // ❌ protected 不允许
private function cleanup(); // ❌ private 不允许
}
- PHP 8.0+ 允许 interface 中定义常量和静态方法,但静态方法必须带
static关键字且有函数体(即不是纯声明),和传统 interface 方法性质不同 - 接口方法默认就是
public,所以显式写public是推荐的(提高可读性),不写也不会报错,但团队规范建议统一加上 - 别试图在 interface 里塞逻辑——哪怕是一行
return true;,那已经不是 interface,该用 trait 或抽象类了
多个 interface 同名方法的参数必须完全兼容
一个类同时 implements A, B,而 A 和 B 都有 handle() 方法,那么这两个 handle() 的签名(参数类型、数量、顺序、返回类型)必须能被同一个实现覆盖。否则会报 Declaration of X::handle() must be compatible with Y::handle()。
例如:
interface Reader {
public function read(string $path): array;
}
interface Writer {
public function read(string $path, bool $raw = false): array; // 多了一个参数
}
class FileReader implements Reader, Writer { ... } // ❌ 报错:参数不兼容
- 解决办法只有两个:要么统一两个 interface 的方法签名(推荐);要么让其中一个 interface 改名,比如
readRaw() - PHP 不支持接口方法重载,也没有“协变参数”这种机制(不像 Java 的 extends T>),所以参数列表差异哪怕只是加个默认值,也算不兼容
- 这问题常出现在引入第三方 SDK 时——你自己的
CacheInterface和 SDK 的Cacheable碰巧都叫get(),但参数对不上,结果一 implement 就崩
interface 不强制要求实现所有方法?不,它强制
只要类声明 implements X,就必须实现 X 中定义的每一个方法,一个都不能少,也不能只实现一部分。漏掉会报 Class Y contains 1 abstract method and must therefore be declared abstract or implement the remaining methods。
注意:这个“必须实现”是硬性语法约束,不是运行时检查。
- 容易踩的坑:升级 PHP 版本后,某个 interface 新增了方法(比如 PHP 8.2 给
Stringable加了新能力),你的老实现类没更新,就会突然报错 - IDE(如 PHPStorm)有时不会实时标红缺失方法,尤其在 interface 被 require_once 动态加载时,得靠
php -l或 CI 流水线暴露问题 - 如果真想“跳过”某些方法,说明设计有问题——interface 职责太重了,该拆分成更小的、正交的 interface(比如
Readable、Writable、Flushable)
interface 的边界感特别强:它不管你怎么实现,只管你有没有承诺。承诺了,就得兑现;没承诺,就别写 implements。很多人卡住,不是因为不会写,而是没想清楚这个“承诺”到底要覆盖哪些场景。











