Skip to content

bool — 布尔类型

概述

bool 是 PHP 中最简单的标量类型,只有两个可能的值:truefalse。布尔值在条件判断、逻辑运算、标志控制等方面有着广泛的应用。理解 PHP 的隐式布尔转换规则(truthy/falsy 值),对于编写正确的条件逻辑至关重要。

前置知识

在阅读本节之前,你需要了解:

  • PHP 条件语句(ifelseelseif
  • 比较运算符(=====!=
  • 逻辑运算符(&&||!

基础概念

true 和 false 关键字

PHP 中布尔值使用两个不区分大小写的关键字表示:

php
<?php
declare(strict_types=1);

$isActive  = true;   // 也可以写成 TRUE、True
$isDeleted = false;  // 也可以写成 FALSE、False

// 但推荐使用小写(PSR-12)

Truthy 和 Falsy 值

当其他类型被用于布尔上下文(如 if 条件)时,PHP 会自动将其转换为 bool。以下值被转换为 false(即 falsy 值):

Falsy 值说明
false布尔值 false
0整数 0
0.0浮点数 0.0
""空字符串
"0"字符串 "0"
[]空数组
nullnull 值
SimpleXML 对象从空元素创建时(旧版 PHP)

所有其他值都被转换为 true(即 truthy 值),包括 -1"false"[0] 等。

语法与代码

布尔类型声明

php
<?php
declare(strict_types=1);

function setDebugMode(bool $enabled): void
{
    echo $enabled ? 'Debug 模式已启用' : 'Debug 模式已关闭';
}

setDebugMode(true);   // Debug 模式已启用
setDebugMode(false);  // Debug 模式已关闭

// 严格模式下传入非 bool 值会抛出 TypeError
// setDebugMode(1); // TypeError!

隐式布尔转换示例

php
<?php
declare(strict_types=1);

// 完整的 falsy 值测试
$falsyValues = [
    'false'     => false,
    'int 0'     => 0,
    'float 0'   => 0.0,
    'empty str' => '',
    'str "0"'   => "0",
    'null'      => null,
    'empty array' => [],
];

foreach ($falsyValues as $label => $value) {
    echo "{$label}: ";
    echo $value ? 'truthy' : 'falsy';
    echo PHP_EOL;
}

// 需要注意的 truthy 值
$truthyValues = [
    'true'      => true,
    'int 1'     => 1,
    'int -1'    => -1,    // 注意:-1 是 truthy!
    'float 0.1' => 0.1,
    '"false"'   => "false", // 注意:字符串 "false" 是 truthy!
    '"0.0"'     => "0.0",  // 注意:字符串 "0.0" 是 truthy!
    '[0]'       => [0],    // 注意:包含 0 的数组是 truthy!
    'object'    => new stdClass(),
];

foreach ($truthyValues as $label => $value) {
    echo "{$label}: ";
    echo $value ? 'truthy' : 'falsy';
    echo PHP_EOL;
}

比较运算返回布尔值

php
<?php
declare(strict_types=1);

// 比较运算符始终返回 bool
$result1 = 10 > 5;      // true
$result2 = 10 === '10'; // false(严格比较)
$result3 = 10 == '10';  // true(弱比较)
$result4 = '' !== null; // true

// 逻辑运算符返回 bool
$result5 = true && false; // false
$result6 = true || false; // true
$result7 = !true;          // false

// 类型检查函数返回 bool
$checks = [
    is_int(42),       // true
    is_string('hi'),  // true
    is_array([]),     // true
    is_null(null),    // true
    is_float(3.14),   // true
];

foreach ($checks as $check) {
    var_dump($check);
}

filter_var 进行布尔验证

php
<?php
declare(strict_types=1);

// filter_var 的 FILTER_VALIDATE_BOOLEAN
// 将各种值转换为规范的 bool
$inputs = [
    true, false, 'yes', 'no', 'on', 'off',
    '1', '0', 'true', 'false', '', 1, 0,
];

foreach ($inputs as $input) {
    $result = filter_var($input, FILTER_VALIDATE_BOOLEAN);
    $export = var_export($input, true);
    $res = var_export($result, true);
    echo "{$export} -> {$res}" . PHP_EOL;
}
// true -> true
// false -> false
// 'yes' -> true
// 'no' -> false
// 'on' -> true
// 'off' -> false
// '1' -> true
// '0' -> false
// 'true' -> true
// 'false' -> false
// '' -> false
// 1 -> true
// 0 -> false

详细说明

bool 值在算术运算中的转换

php
<?php
declare(strict_types=1);

// true 转为 1,false 转为 0
echo true + true;       // 2
echo true + false;      // 1
echo false + false;     // 0
echo true * 10;         // 10
echo false * 10;        // 0

// 用于计数器等场景
$features = [
    'debug' => true,
    'cache' => false,
    'log'   => true,
];

$enabledCount = 0;
foreach ($features as $feature) {
    $enabledCount += (int)$feature; // true->1, false->0
}
echo "启用了 {$enabledCount} 个功能"; // 启用了 2 个功能

严格布尔检查

php
<?php
declare(strict_types=1);

// 区分 "变量存在且为 false" 与 "变量不存在或为 null"
function hasValue(mixed $value): bool
{
    return $value !== null;
}

function isTruthy(mixed $value): bool
{
    return (bool)$value === true;
}

function isExactlyFalse(mixed $value): bool
{
    return $value === false;
}

// 测试
var_dump(hasValue(false));        // bool(true) — 变量存在
var_dump(isTruthy(false));        // bool(false) — 值为 falsy
var_dump(isExactlyFalse(false));  // bool(true) — 值就是 false
var_dump(isExactlyFalse(null));   // bool(false) — null 不是 false

实战示例

特性标志管理

php
<?php
declare(strict_types=1);

/**
 * 应用特性标志管理系统
 */
readonly class FeatureFlags
{
    public function __construct(
        private readonly array $flags = []
    ) {}

    public function isEnabled(string $flag): bool
    {
        return $this->flags[$flag] ?? false;
    }

    public function enable(string $flag): void
    {
        $this->flags[$flag] = true;
    }

    public function disable(string $flag): void
    {
        $this->flags[$flag] = false;
    }

    public function when(string $flag, callable $callback): mixed
    {
        if ($this->isEnabled($flag)) {
            return $callback();
        }
        return null;
    }

    public function unless(string $flag, callable $callback): mixed
    {
        if (!$this->isEnabled($flag)) {
            return $callback();
        }
        return null;
    }
}

// 使用示例
$features = new FeatureFlags([
    'dark_mode'     => true,
    'new_dashboard' => false,
    'beta_api'      => true,
]);

// 条件执行
$features->when('dark_mode', fn() => echo '暗色模式已激活' . PHP_EOL);
$features->unless('new_dashboard', fn() => echo '使用旧版仪表盘' . PHP_EOL);

注意事项

1. 不要用 1/0 代替 true/false

php
<?php
declare(strict_types=1);

// 不推荐
$isAdmin = 1;

// 推荐
$isAdmin = true;

2. 字符串 "false" 是 truthy

php
<?php
declare(strict_types=1);

// 常见陷阱
$str = "false";
if ($str) {
    echo "这会执行!'false' 字符串是 truthy";
}

// 正确判断方式
if ($str === true) {
    echo "不会执行";
}

// 或使用 filter_var
if (filter_var($str, FILTER_VALIDATE_BOOLEAN)) {
    echo "不会执行";
}

最佳实践

  1. 使用 true/false 而非 1/0:语义更清晰
  2. 布尔参数用 bool 类型声明:严格模式下自动检查
  3. 注意 "0" 是 falsy:处理表单输入时特别注意
  4. 使用 === 比较:区分 falsenull0""
  5. filter_var 转换用户输入:将字符串 "true"/"false" 转为 bool
  6. 命名用 is/has/can 前缀:布尔变量使用语义化命名

下一节

下一节将详细介绍 int 整数类型,了解整数的语法、进制表示、范围限制和溢出处理。

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接