Skip to content

int — 整数类型

概述

int 是 PHP 中的标量整数类型,用于表示没有小数部分的数值。PHP 的整数范围取决于平台架构(32 位或 64 位),可以使用十进制、二进制、八进制和十六进制四种表示法。理解整数的范围限制、溢出处理和进制转换,对于数值计算和位运算非常重要。

前置知识

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

  • 数值的基本概念和运算
  • 二进制、八进制、十六进制的基本知识
  • 位运算符的基础知识
  • PHP_INT_MAX 和 PHP_INT_SIZE 常量

基础概念

整数的范围

平台大小最小值最大值
32 位4 字节-2,147,483,6482,147,483,647
64 位8 字节-9,223,372,036,854,775,8089,223,372,036,854,775,807
php
<?php
declare(strict_types=1);

echo PHP_INT_SIZE;     // 8(64 位系统)
echo PHP_INT_MAX;      // 9223372036854775807
echo PHP_INT_MIN;      // -9223372036854775808(PHP 7.0+)

语法与代码

四种进制表示

php
<?php
declare(strict_types=1);

// 十进制(默认)
$decimal = 42;

// 二进制(0b 前缀,PHP 5.4+)
$binary = 0b101010; // 42

// 八进制(0 前缀)
$octal = 052; // 42

// 十六进制(0x 前缀)
$hex = 0x2A; // 42

echo $decimal; // 42
echo $binary;  // 42
echo $octal;   // 42
echo $hex;     // 42

// 负数
$negHex = -0xFF; // -255

整数类型声明

php
<?php
declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

function factorial(int $n): int
{
    if ($n < 0) {
        throw new InvalidArgumentException('阶乘仅接受非负整数');
    }
    if ($n === 0 || $n === 1) {
        return 1;
    }
    return $n * factorial($n - 1);
}

echo factorial(5); // 120

整数溢出处理

php
<?php
declare(strict_types=1);

$large = PHP_INT_MAX;
echo $large;          // 9223372036854775807
echo $large + 1;      // 9.2233720368548E+18(自动转为 float!)

// 使用 GMP 处理超大整数
$big1   = gmp_init('99999999999999999999');
$big2   = gmp_init('1');
$result = gmp_add($big1, $big2);
echo gmp_strval($result); // "100000000000000000000"

进制转换函数

php
<?php
declare(strict_types=1);

echo decbin(42);  // "101010"
echo decoct(42);  // "52"
echo dechex(42);  // "2a"

echo bindec('101010');  // 42
echo octdec('52');      // 42
echo hexdec('2a');      // 42

echo base_convert('101010', 2, 16); // "2a"
echo base_convert('255', 10, 36);   // "73"

详细说明

整数除法

php
<?php
declare(strict_types=1);

var_dump(10 / 3);        // float(3.3333...)
var_dump(10 / 2);        // float(5.0)  即使整除也返回 float!
var_dump(intdiv(10, 3));  // int(3)(PHP 7.0+)
var_dump(7 % 2);          // int(1) 取模

位运算符

php
<?php
declare(strict_types=1);

$a = 0b1100; // 12
$b = 0b1010; // 10

echo $a & $b;  // 8  (0b1000) — 按位与
echo $a | $b;  // 14 (0b1110) — 按位或
echo $a ^ $b;  // 6  (0b0110) — 按位异或
echo ~$a;      // -13        — 按位取反
echo $a << 2;  // 48         — 左移
echo $a >> 1;  // 6          — 右移

实战示例

整数工具类

php
<?php
declare(strict_types=1);

class IntUtils
{
    public static function isInRange(int $value, int $min, int $max): bool
    {
        return $value >= $min && $value <= $max;
    }

    public static function clamp(int $value, int $min, int $max): int
    {
        return max($min, min($max, $value));
    }

    public static function formatBytes(int $bytes, int $precision = 2): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes = max($bytes, 0);
        $pow = (int)floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= 1024 ** $pow;
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

echo IntUtils::formatBytes(1024);     // "1 KB"
echo IntUtils::formatBytes(1048576);  // "1 MB"
echo IntUtils::clamp(150, 0, 100);    // 100

注意事项

1. PHP_INT_MAX / -1 不等于 PHP_INT_MIN

php
<?php
declare(strict_types=1);

var_dump(PHP_INT_MAX / -1); // float(-9.2233720368548E+18)
// 因为 PHP_INT_MAX + 1 已经溢出为 float

2. 前导零陷阱

php
<?php
declare(strict_types=1);

$num = 0123; // 八进制的 83,不是十进制的 123!

前导零陷阱

0 开头的整数字面量会被解释为八进制。PHP 8.1+ 中产生弃用警告。

最佳实践

  1. 使用 int 类型声明:所有整数参数和返回值都声明类型
  2. 使用 intdiv():进行整数除法避免意外的 float
  3. 使用 random_int():安全随机数
  4. 检查范围:使用 FILTER_VALIDATE_INTmin_range/max_range
  5. 注意溢出:大数运算时检查 PHP_INT_MAX

下一节

下一节将详细介绍 float 浮点数类型。

进阶用法

调试与测试技巧

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');

参考链接