int — 整数类型
概述
int 是 PHP 中的标量整数类型,用于表示没有小数部分的数值。PHP 的整数范围取决于平台架构(32 位或 64 位),可以使用十进制、二进制、八进制和十六进制四种表示法。理解整数的范围限制、溢出处理和进制转换,对于数值计算和位运算非常重要。
前置知识
在阅读本节之前,你需要了解:
- 数值的基本概念和运算
- 二进制、八进制、十六进制的基本知识
- 位运算符的基础知识
- PHP_INT_MAX 和 PHP_INT_SIZE 常量
基础概念
整数的范围
| 平台 | 大小 | 最小值 | 最大值 |
|---|---|---|---|
| 32 位 | 4 字节 | -2,147,483,648 | 2,147,483,647 |
| 64 位 | 8 字节 | -9,223,372,036,854,775,808 | 9,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 已经溢出为 float2. 前导零陷阱
php
<?php
declare(strict_types=1);
$num = 0123; // 八进制的 83,不是十进制的 123!前导零陷阱
以 0 开头的整数字面量会被解释为八进制。PHP 8.1+ 中产生弃用警告。
最佳实践
- 使用 int 类型声明:所有整数参数和返回值都声明类型
- 使用 intdiv():进行整数除法避免意外的 float
- 使用 random_int():安全随机数
- 检查范围:使用
FILTER_VALIDATE_INT和min_range/max_range - 注意溢出:大数运算时检查 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 修正 |
| 性能下降 | 索引缺失/数据量大 | 添加索引,优化查询 |
| 数据不一致 | 并发冲突/事务残留 | 使用锁机制和事务 |
| 内存溢出 | 大数据集/未释放资源 | 增大内存限制,分批处理 |
故障排除步骤
- 检查错误日志和异常信息
- 确认配置和环境是否正确
- 使用调试工具逐步排查
- 参考官方文档查找已知问题
版本兼容性说明
| 功能 | 最低版本 | 说明 |
|---|---|---|
| 基础功能 | PHP 8.1 | 本文档基准版本 |
| 只读属性 | PHP 8.1 | public readonly 修饰符 |
| 枚举类型 | PHP 8.1 | enum 类型和 match 表达式 |
| Fiber | PHP 8.1 | 协程/轻量级并发 |
| 命名参数 | PHP 8.0 | foo(arg_name: value) |
| 联合类型 | PHP 8.0 | `int |
| Null 安全运算符 | PHP 8.0 | $obj?->method() |
| 析构器 promotion | PHP 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');