is_bool

is_bool(mixed $value): bool

检测变量是否为布尔类型。

C C23

C23
#include <stdbool.h>
#include <stdio.h>

#define is_bool(x) _Generic((x), _Bool: 1, default: 0)

int main(void) {
    bool b = true;
    int i = 1;
    printf("%d %d %d\n", is_bool(b), is_bool(i), is_bool("true"));
    return 0;
}
输出
1 0 0

C++ C++26

C++26
#include <iostream>
#include <type_traits>
int main() {
    bool b = true;
    int i = 1;
    std::cout << std::boolalpha << std::is_same_v<decltype(b), bool> << " "
              << std::is_same_v<decltype(i), bool> << "\n";
    return 0;
}
输出
true false

C# v11.0.100

v11.0.100
object[] xs = { true, 1, "true" };
foreach (object x in xs) {
    Console.WriteLine(x is bool);
}
输出
True
False
False

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
    xs := []any{true, 1, "true"}
    for _, x := range xs {
        _, ok := x.(bool)
        fmt.Println(ok)
    }
}
输出
true
false
false

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        Object[] xs = { true, 1, "true" };
        for (Object x : xs) {
            System.out.println(x instanceof Boolean);
        }
    }
}
输出
true
false
false

JavaScript v26.13.1

v26.13.1
console.log([typeof true === "boolean", typeof 1 === "boolean", typeof "true" === "boolean"]);
输出
[ true, false, false ]

PHP v8.6.0

v8.6.0
echo json_encode([is_bool(true), is_bool(1), is_bool("true")]);
输出
[true,false,false]

Python v3.15.2

v3.15.2
print([isinstance(x, bool) for x in [True, 1, "true"]])
输出
[True, False, False]

Rust v1.99.1

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

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

TypeScript v26.13.1

v26.13.1
const xs: (boolean | number | string)[] = [true, 1, "true"];
console.log(xs.map((x) => typeof x === "boolean"));
输出
[ true, false, false ]

语言差异说明

C:C99 起 bool(宏,展开为 _Bool)与 int 是不同类型,_Generic 可区分。

C++:bool 是独立基本类型。

C#:动态容器惯用 is bool。

Go:动态容器惯用断言 .(bool)。

Java:动态容器惯用 instanceof Boolean。

JavaScript:更微妙——1 == true 成立(宽松比较先转数字),typeof 1 是 "number" 而 typeof true 是 "boolean",三等号 1 === true 不成立。

PHP:1 与 true 的关系是本条的核心差异——宽松比较 1 == true 成立但 is_bool(1) 为 false(类型严格)。

Python:方向相反——bool 是 int 的子类,True == 1 成立且 True + True == 2,isinstance(1, bool) 为 false 但 isinstance(True, int) 为 true;写「只接受布尔」的函数惯用 isinstance(x, bool),写「接受整数」时必须意识到布尔会混入。

Rust:动态容器惯用 Any::is::<bool>()。