class_exists
class_exists(string $class, bool $autoload = true): bool
检查类是否已定义(或能否通过自动加载器加载),与 interface_exists/enum_exists 同族。
C C23
#include <stdio.h>
/* C 没有类的概念——最接近的对应是「类型/符号在编译期是否已声明」;
sizeof 能通过即证明类型已知 */
struct Suit {
int rank;
};
int main(void) {
printf("%zu\n", sizeof(struct Suit)); /* 编译期存在性证明 */
struct Suit s = {1};
printf("%d\n", s.rank == 1 ? 1 : 0);
return 0;
}
4 1
C++ C++26
#include <iostream>
#include <type_traits>
class Suit {};
int main() {
// C++ 编译期绑定;「类型是否存在」变成模板问题。
// trait 检测是编译期探测(class_exists 的对应物)
std::cout << std::boolalpha;
std::cout << std::is_class_v<Suit> << "\n";
std::cout << std::is_class_v<int> << "\n";
return 0;
}
true false
C# v11.0.100
// Type.GetType 按名在已加载程序集中解析;throwOnError:false 把「缺失」
// 变成 null(对应 PHP 的 false)
Console.WriteLine(Type.GetType("System.String") != null);
Console.WriteLine(Type.GetType("NoSuch.Class.A20", throwOnError: false) == null);
// 接口一族(interface_exists 的对应物)
Console.WriteLine(typeof(System.Collections.IEnumerable).IsInterface);
True True True
Go v1.27.4
package main
import "fmt"
type Suit int
func main() {
// Go 在编译期解析所有标识符;「这个类型存在吗」不是运行期问题——
// 注册表 map 模式是运行期的对应形态
registry := map[string]any{"Suit": Suit(0)}
_, ok := registry["Suit"]
fmt.Println(ok)
_, ok = registry["NoSuchClassA20"]
fmt.Println(ok)
}
true false
Java v27.0.1
// Class.forName 探测类路径;缺失的类抛 ClassNotFoundException——
// try/catch 把异常转成布尔(对应 PHP 的 false)
class Main {
public static void main(String[] args) {
System.out.println(exists("java.util.Map"));
System.out.println(exists("java.util.NoSuchClassA20"));
}
static boolean exists(String name) {
try {
Class.forName(name);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
true false
JavaScript v26.13.1
// JS 没有类表;typeof X !== "undefined" 探测运行期存在性,
// 对未声明标识符也不会抛错
console.log(typeof Map !== "undefined");
console.log(typeof NoSuchClassA20 !== "undefined");
class Suit {}
console.log(typeof Suit !== "undefined");
true false true
PHP v8.6.0
// class_exists 是「类」这一族的探测;第二参数决定是否触发自动加载队列
// (与 spl_autoload_register 配对)
enum Suit: string { case Hearts = "H"; }
var_dump(class_exists("stdClass")); // 内置类
var_dump(class_exists("NoSuchClassA20")); // 不存在,自动加载器也找不到
var_dump(interface_exists("Traversable")); // 接口一族
var_dump(enum_exists("Suit")); // 枚举一族(8.1+)
var_dump(class_exists("Traversable")); // 接口不是类
bool(true) bool(false) bool(true) bool(true) bool(false)
Python v3.15.2
import importlib.util
import json
# importlib.util.find_spec 定位模块但不导入——相当于 autoload=false;
# 导入后的成员用 hasattr 检查
def module_exists(name):
spec = importlib.util.find_spec(name)
return spec is not None
print(module_exists("json"))
print(module_exists("no_such_module_a20"))
print("JSONDecoder" in dir(json))
True False True
Rust v1.99.1
// Rust 全部编译期绑定;存在性探测是 trait 层面的问题,不是运行期查找。
// 注册表展示运行期的对应形态:
use std::collections::HashMap;
fn main() {
let mut registry: HashMap<&str, fn() -> &'static str> = HashMap::new();
registry.insert("Suit", || "hearts");
println!("{}", registry.contains_key("Suit"));
println!("{}", registry.contains_key("NoSuchClassA20"));
}
true false
TypeScript v26.13.1
// 与 JS 相同的运行时探测;声明了却不存在的名字在编译期就被拦下,
// 所以运行时探测只针对动态键
console.log(typeof Map !== "undefined");
const g = globalThis as Record<string, unknown>;
console.log(typeof g["NoSuchClassA20"] !== "undefined");
class Suit {}
console.log(typeof Suit !== "undefined");
true false true
语言差异说明
C:没有运行期类型查询——引用未定义类型是编译错误;#ifdef/预处理器宏是「条件存在」的唯一机制,运行期动态探测只有 dlsym(符号级)。
C++:编译期绑定;类型探测在模板元编程层完成(std::is_class_v 等 trait,示例)——与 PHP 运行期查表是两个维度。
C#:Type.GetType + throwOnError:false(示例);注意它只查已加载程序集,跨程序集要用 Assembly.GetType——与 PHP「autoload=true 时触发加载器」的语义对应。
Go:编译期解析一切标识符,「类存在与否」不是运行期问题(示例如实用注册表模拟);特性探测走 build tag,也是编译期。
Java:Class.forName 查当前类加载器类路径,缺失抛异常(示例转布尔);接口用 clazz.isInterface(),与 PHP 的 interface_exists 分法一致。
JavaScript:typeof 是对未声明标识符唯一不抛错的探测(示例);但类声明是块级绑定,查不到闭包/模块作用域里的类——语言层面没有全局类表。
PHP:autoload 交互是本条目核心——第二参数 allow_autoload 默认 true,查询缺失类会触发 spl_autoload_register 注册的队列(可能把类「查出存在」);传 false 只查已定义类表;一族三个函数:class_exists/interface_exists/enum_exists,接口和枚举不算类(示例末行)。
Python:模块级探测用 importlib.util.find_spec(不执行导入,对应 autoload=false);类/对象级用 hasattr;无「枚举存在性」专门函数——都是普通对象属性。
Rust:编译期绑定,类型不存在即编译错误;「存在性」在 trait/泛型约束层表达(如特化探测宏 trait Variant 惯用法),运行期查表演示仅示意。
TypeScript:编译期把「未定义名字」直接拦下(typeof 只对动态键仍有意义,示例);keyof typeof / 条件类型是类型层探测。