method_exists

method_exists(object|string $objectOrClass, string $method): bool

检查类或对象上是否存在某个方法。

C C23

C23
#include <stdio.h>

/* C 没有方法:用「操作表」结构体模拟方法集,
   「method_exists」就是对槽位判空 */
typedef struct {
    const char *(*hello)(void);
    const char *(*goodbye)(void);
} GreeterOps;

static const char *hello_impl(void) {
    return "hi";
}

int main(void) {
    GreeterOps ops = { .hello = hello_impl, .goodbye = NULL };
    printf("hello: %s\n", ops.hello ? "true" : "false");
    printf("goodbye: %s\n", ops.goodbye ? "true" : "false");
    return 0;
}
输出
hello: true
goodbye: false

C++ C++26

C++26
#include <iostream>
#include <string>
#include <type_traits>

struct Greeter {
    std::string hello() { return "hi"; }
};

/* 编译期成员探测(C++17 惯用法):void_t 兜住 SFINAE 失败 */
template <typename T, typename = void>
struct has_hello : std::false_type {};

template <typename T>
struct has_hello<T, std::void_t<decltype(std::declval<T&>().hello())>>
    : std::true_type {};

template <typename T, typename = void>
struct has_goodbye : std::false_type {};

template <typename T>
struct has_goodbye<T, std::void_t<decltype(std::declval<T&>().goodbye())>>
    : std::true_type {};

int main() {
    Greeter g;
    std::cout << std::boolalpha;
    std::cout << "hello: " << has_hello<Greeter>::value << "\n";
    std::cout << "goodbye: " << has_goodbye<Greeter>::value << "\n";
    std::cout << g.hello() << "\n";
    return 0;
}
输出
hello: true
goodbye: false
hi

C# v11.0.100

v11.0.100
using System;
using System.Reflection;

Type t = typeof(Greeter); // 经反射查 MethodInfo
Console.WriteLine("hello: " + (t.GetMethod("Hello") != null));
Console.WriteLine("goodbye: " + (t.GetMethod("Goodbye") != null));

class Greeter
{
    public string Hello() => "hi";
}
输出
hello: True
goodbye: False

Go v1.27.4

v1.27.4
package main

import "fmt"

type Greeter struct{}

func (Greeter) Hello() string {
	return "hi"
}

func main() {
	// 没有 method_exists:方法集在编译期已定死;
	// 运行期只能经接口断言问「会不会某行为」
	var g interface {
		Hello() string
	} = Greeter{}
	fmt.Println(g.Hello())
	_, ok := any(Greeter{}).(fmt.Stringer)
	fmt.Println("has String():", ok)
}
输出
hi
has String(): false

Java v27.0.1

v27.0.1
import java.lang.reflect.Method;

public class Main {
    static class Greeter {
        public String hello() {
            return "hi";
        }
    }

    // 反射式查询:遍历公共方法名(含继承自 Object 的)
    static boolean hasMethod(Class<?> c, String name) {
        for (Method m : c.getMethods()) {
            if (m.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Class<Greeter> c = Greeter.class;
        System.out.println("hello: " + hasMethod(c, "hello"));
        System.out.println("goodbye: " + hasMethod(c, "goodbye"));
    }
}
输出
hello: true
goodbye: false

JavaScript v26.13.1

v26.13.1
class Greeter {
  hello() {
    return "hi";
  }
}
const g = new Greeter();
// typeof 检查同时回答「存在且可调用」
console.log(typeof g.hello === "function", typeof g.goodbye === "function");
输出
true false

PHP v8.6.0

v8.6.0
class Greeter {
    public function hello(): string {
        return 'hi';
    }
}
// method_exists 只认已声明方法;__call 魔术转发要用 is_callable
var_dump(method_exists(Greeter::class, 'hello'));
var_dump(method_exists(Greeter::class, 'goodbye'));
输出
bool(true)
bool(false)

Python v3.15.2

v3.15.2
class Greeter:
    def hello(self):
        return "hi"


g = Greeter()
# hasattr 回答「属性存在」,callable() 再收窄为「可调用」
print(hasattr(g, "hello"), hasattr(g, "goodbye"))
print(callable(getattr(g, "hello", None)))
输出
True False
True

Rust v1.99.1

v1.99.1
struct Greeter;

impl Greeter {
    fn hello(&self) -> String {
        String::from("hi")
    }
}

fn main() {
    // 没有 method_exists:方法集在编译期定死——
    // 调不存在的方法是编译错误,不是运行期查询
    let g = Greeter;
    println!("{}", g.hello());
    println!("no runtime method check in Rust");
}
输出
hi
no runtime method check in Rust

TypeScript v26.13.1

v26.13.1
class Greeter {
  hello(): string {
    return "hi";
  }
}
const g = new Greeter();
console.log(typeof g.hello === "function", typeof (g as any).goodbye === "function");
// typeof 一并回答「存在且可调用」;as any 只为放行演示
输出
true false

语言差异说明

PHP:method_exists 只看「已声明/继承的方法」,不认 __call 魔术方法——想覆盖魔术转发要用 is_callable(示例的 goodbye 若经 __call 转发,method_exists 仍是 false);入参收类名或对象均可。

C:无方法系统(示例用「操作表」结构体模拟):成员函数指针判空就是 method_exists 的手工等价物,这是 C 语言 OOP 风格(glib/GObject)的真实做法。

C++:无运行时反射——method_exists 由模板元编程在编译期回答(示例的 void_t + decltype 惯用法);C++20 起可写得更短(requires 表达式),本示例保持 C++17 口径与构建参数一致。

C#:GetMethod(name)(示例)返回 MethodInfo,查不到返回 null;注意默认只搜公共方法,私有重载要传 BindingFlags。

Go:没有 method_exists——方法集在编译期定死,拼错方法名直接编译错误;运行期的对应物是接口断言(示例):问「这个值会不会某行为」,而不是「这个类型有没有某名字」。

Java:反射 getMethods()(示例)遍历比对方法名;另一姿势是 getMethod(name) 捕获 NoSuchMethodException;getMethods 只给公共方法,任意可见性用 getDeclaredMethods 逐级向上。

JavaScript:没有同名 API,惯用 typeof obj.method === "function"(示例)同时回答「存在且可调用」;原型链上的方法经实例访问同样能探到。

Python:hasattr(示例)是属性存在性,callable() 收窄到可调用——两步合起来才是 method_exists 的等价物;hasattr 内部就是 getattr 试错。

Rust:无运行时方法查询(示例如实展示):方法解析在编译期完成,trait 约束也只在编译期成立;想问「运行期值支持某行为」用的是 dyn Any 向下转型或 trait 对象,但仍查不到「方法名清单」。

TypeScript:与 JS 同款 typeof 检查(示例);不同处在于编译期还有严格类型守卫,as any 绕开检查只用于演示——生产代码应在类型层面杜绝拼错方法名。