interface_exists / trait_exists

interface_exists(string $interface, bool $autoload = true): bool / trait_exists(string $trait, bool $autoload = true): bool

检查接口或 trait 是否已定义(可触发自动加载);与 class_exists/enum_exists 成族,是 PHP 运行期类型表的一角。

C C23

C23
#include <stdio.h>

/* C 没有接口关键字——契约是一张函数指针结构体(vtable);
   「实现」意味着把表填满 */
typedef struct {
    const char *(*kind)(void);
} Drawable;

static const char *circle_kind(void) { return "circle"; }

int main(void) {
    Drawable d = { circle_kind }; /* 这张表本身就是接口 */
    printf("%d\n", d.kind != NULL); /* 初始化即满足契约 */
    printf("%s\n", d.kind());
    return 0;
}
输出
1
circle

C++ C++26

C++26
#include <iostream>

class Drawable { // 接口惯用法:纯虚函数、无状态、虚析构
public:
    virtual ~Drawable() = default;
    virtual const char* kind() const = 0;
};

class Circle : public Drawable {
public:
    const char* kind() const override { return "circle"; }
};

int main() {
    Drawable* d = new Circle();
    // 运行期「接口检查」= 这个对象是否满足契约
    std::cout << (d != nullptr) << "\n";
    std::cout << d->kind() << "\n";
    delete d;
    return 0;
}
输出
1
circle

C# v11.0.100

v11.0.100
using System;

interface Drawable { string Kind(); }

class Circle : Drawable {
    public string Kind() => "circle";
}

class MainClass {
    static void Main() {
        // 显式接口阵营:反射携带 IsInterface 标记
        Console.WriteLine(typeof(IDisposable).IsInterface);
        Console.WriteLine(typeof(string).IsInterface);
        // 按名探测已加载程序集(interface_exists 的对应物)
        Type t = Type.GetType("System.IDisposable");
        Console.WriteLine(t != null && t.IsInterface);
        Console.WriteLine(new Circle() is Drawable);
    }
}
输出
True
False
True
True

Go v1.27.4

v1.27.4
package main

import "fmt"

// Go 属隐式阵营:接口被结构化满足,
// 没有声明点注册,因此根本不存在「exists」函数
type Drawable interface{ Kind() string }

type Circle struct{}

func (Circle) Kind() string { return "circle" }

func main() {
	var d Drawable = Circle{} // 赋值本身就是证明
	fmt.Println(d.Kind())
	// 失败的接口转换是唯一的运行期「满足性」探针
	if _, ok := any(Circle{}).(Drawable); ok {
		fmt.Println("satisfies")
	}
}
输出
circle
satisfies

Java v27.0.1

v27.0.1
interface Drawable { // 隐式 static 且 abstract
    String kind();
}

class Circle implements Drawable {
    public String kind() { return "circle"; }
}

class Main {
    public static void main(String[] args) throws Exception {
        // 显式接口阵营:Class 携带 isInterface 标记
        System.out.println(Drawable.class.isInterface());
        System.out.println(String.class.isInterface());
        // 按名探测类路径(interface_exists 的对应物)
        Class<?> c = Class.forName("java.lang.Runnable");
        System.out.println(c.isInterface());
    }
}
输出
true
false
true

JavaScript v26.13.1

v26.13.1
// JS 运行期没有接口概念——鸭子类型取而代之:
// 对象「实现」它恰好拥有的方法
const circle = {
    kind() { return "circle"; },
};

// 结构化探查:没有注册表、没有元数据,只有对象自身
console.log(typeof circle.kind === "function");
console.log("implements" in circle); // 没有可查询的接口元数据
输出
true
false

PHP v8.6.0

v8.6.0
// 类型表中接口 / trait 两个角落的存在性探测
interface Drawable {}
trait Timestamped {}

var_dump(interface_exists('Drawable'));      // 已定义接口
var_dump(interface_exists('Timestamped'));   // trait 不是接口
var_dump(trait_exists('Timestamped'));       // 已定义 trait
var_dump(trait_exists('Drawable'));          // 接口不是 trait
var_dump(interface_exists('Traversable'));   // 内置接口
var_dump(interface_exists('NoSuchIface', false)); // 禁用自动加载
// class_alias 对接口和 trait 同样有效(与 class_exists 同族)
输出
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

Python v3.15.2

v3.15.2
from abc import ABC, abstractmethod
import inspect

# ABC 维护(虚拟)子类注册表——在 Python 隐式实现文化里
# 最接近 interface_exists 的东西
class Drawable(ABC):
    @abstractmethod
    def kind(self):
        ...


class Circle(Drawable):
    def kind(self):
        return "circle"


print(issubclass(Circle, Drawable))
print(len(Drawable.__subclasses__()) >= 1)  # 注册表可查询
print(inspect.isabstract(Drawable))
输出
True
True
True

Rust v1.99.1

v1.99.1
// Rust trait 是编译期概念:无注册表、无 exists 探针——
// impl 块在编译期被静态检查,之后即被遗忘
trait Drawable {
    fn kind(&self) -> &'static str;
}

struct Circle;
impl Drawable for Circle {
    fn kind(&self) -> &'static str { "circle" }
}

fn render(d: &dyn Drawable) {
    println!("{}", d.kind());
}

fn main() {
    render(&Circle); // 满足性在编译期已证毕
}
输出
circle

TypeScript v26.13.1

v26.13.1
// TS 接口只在编译期存在——被擦除后运行期没有 interface_exists;
// 类型检查器本身就是探针
interface Drawable {
    kind(): string;
}

class Circle implements Drawable {
    kind() { return "circle"; }
}

const c: Drawable = new Circle(); // 赋值在编译期被检查
console.log(typeof c.kind === "function"); // 运行期只见方法
输出
true

语言差异说明

C:无接口关键字——契约是函数指针结构体(vtable,示例);「存在性」= 表已填满,初始化时成立。

C++:接口惯用法是纯虚基类(示例);C++20 concept 把接口约束提进编译期模板元编程;运行期判断只能问「对象是否可转换为该接口指针」。

C#:显式接口阵营——typeof(X).IsInterface(示例);按名探测用 Type.GetType;与 Java 的 isInterface 同构。trait 无对应物(mixin 历史上有扩展方法近似)。

Go:隐式阵营代表——接口由方法集结构化满足,无声明点注册,因此无 exists 概念(示例:赋值与类型断言即全部探针);interface{}/any 是空接口。

Java:显式阵营——X.class.isInterface()(示例);按名用 Class.forName;trait 无对应物。

JavaScript:运行期无接口——鸭子类型(示例);Symbol 协议是唯一的「结构化契约」近似。

PHP:与 class_exists/enum_exists 成族收口——interface_exists/trait_exists 第二参数同样控制 autoload;接口与 trait 互不兼容(示例中间四行);trait 是编译期展平进类的 mixin,运行期无独立实体——这是 trait_exists 存在的意义(探测定义);class_alias 对接口/trait 有效。教学点「显式 vs 隐式两派」:PHP/Java/C#/C++ 属显式声明阵营,Go/Rust/TS/JS 属隐式结构阵营。

Python:ABC 注册表可查询(__subclasses__、示例);鸭子类型文化里 isinstance/issubclass 是「显式化」信号;abc.register 可虚拟注册无关类。

Rust:trait 编译期检查后即遗忘(示例);无运行期注册表;dyn Trait 的满足性由编译器担保。

TypeScript:接口编译期擦除(示例)——implements 违反在编译期报错,运行期无任何痕迹。