is_callable

is_callable(mixed $value, bool $syntax_only = false, string &$callable_name = null): bool

检测值在当前作用域是否可以像函数一样调用(闭包、函数名字符串或 [对象, 方法名] 数组)。

C C23

C23
#include <stdio.h>

typedef int (*fn_ptr)(void);

int answer(void) {
    return 42;
}

int main(void) {
    fn_ptr f = answer;
    fn_ptr g = NULL;
    printf("%d %d\n", f != NULL, g != NULL);
    return 0;
}
输出
1 0

C++ C++26

C++26
#include <iostream>
int answer() {
    return 42;
}
int main() {
    int (*f)() = answer;
    int (*g)() = nullptr;
    std::cout << std::boolalpha << (f != nullptr) << " " << (g != nullptr) << "\n";
    return 0;
}
输出
true false

C# v11.0.100

v11.0.100
Func<int> f = () => 42;
object notCallable = 42;
Console.WriteLine($"{f is Delegate} {notCallable is Delegate}");
输出
True False

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "reflect"
)

func answer() int {
    return 42
}

func main() {
    fmt.Println(reflect.ValueOf(answer).Kind() == reflect.Func,
        reflect.ValueOf(42).Kind() == reflect.Func)
}
输出
true false

Java v27.0.1

v27.0.1
import java.util.concurrent.Callable;

public class Main {
    public static void main(String[] args) {
        Callable<Integer> f = () -> 42;
        Object notCallable = 42;
        System.out.println((f instanceof Callable) + " " + (notCallable instanceof Callable));
    }
}
输出
true false

JavaScript v26.13.1

v26.13.1
console.log([typeof (() => 1) === "function", typeof 42 === "function", typeof "strlen" === "function"]);
输出
[ true, false, false ]

PHP v8.6.0

v8.6.0
echo json_encode([is_callable(fn() => 1), is_callable("strlen"), is_callable(42)]);
输出
[true,true,false]

Python v3.15.2

v3.15.2
print([callable(lambda: 1), callable(42), callable("len")])
输出
[True, False, False]

Rust v1.99.1

v1.99.1
use std::any::Any;

fn answer() -> i32 {
    42
}

fn main() {
    let f: fn() -> i32 = answer;
    let xs: Vec<Box<dyn Any>> = vec![Box::new(f), Box::new(42i32)];
    for x in &xs {
        println!("{}", x.is::<fn() -> i32>());
    }
}
输出
true
false

TypeScript v26.13.1

v26.13.1
const xs: unknown[] = [() => 1, 42, "strlen"];
console.log(xs.map((x) => typeof x === "function"));
输出
[ true, false, false ]

语言差异说明

C:无运行时类型系统,惯用函数指针判空:指针非 NULL 即「可调用」。

C++:无运行时类型系统,惯用函数指针判空;现代写法可用 std::invocable 概念在编译期约束。

C#:带类型系统的替代——is Delegate。

Go:带类型系统的替代——reflect.Kind() == reflect.Func。

Java:带类型系统的替代——instanceof Callable(函数式接口)。

JavaScript:用 typeof x === "function"(类也是 function,但类的实例不是)。

PHP:的 is_callable 是所有语言里最宽的:除闭包外,内置/自定义函数的名字字符串("strlen",第二列 true)与 [对象, "方法名"] 数组都算可调用(回调场景的历史载体),$syntax_only = true 时只查语法不查作用域;第三参数还能带回可调用体的规范名。

Python:callable() 只认实现了 __call__ 的对象——"len" 字符串不可调用(false),len 本身才可调用。

Rust:编译期即知类型,运行时仅能对 fn 指针做 Any::is::<fn() -> i32>() 下行判断。

TypeScript:同 JS,typeof x === "function"。