iterable — 可迭代类型
概述
iterable 是 PHP 7.1 引入的伪类型,用作参数或返回值的类型声明,表示函数接受任何可遍历的值。iterable 可以是数组或实现了 Traversable 接口的对象(如 Generator)。
前置知识
在阅读本节之前,你需要了解:
foreach循环的基本用法Traversable接口的概念- Generator(生成器)的基本用法
基础概念
iterable 可以接受什么
| 类型 | 是否可迭代 | 说明 |
|---|---|---|
array | 是 | PHP 内置数组 |
Traversable 实现类 | 是 | ArrayIterator、Generator 等 |
stdClass | 否 | 不可直接 foreach |
| 标量值 | 否 |
语法与代码
iterable 参数声明
php
<?php
declare(strict_types=1);
function joinStrings(iterable $items, string $sep = ', '): string
{
$result = [];
foreach ($items as $item) {
$result[] = (string)$item;
}
return implode($sep, $result);
}
echo joinStrings(['a', 'b', 'c'], '-'); // a-b-citerable 返回值声明
php
<?php
declare(strict_types=1);
function rangeGenerator(int $start, int $end): iterable
{
for ($i = $start; $i <= $end; $i++) {
yield $i;
}
}
function filterEven(iterable $numbers): iterable
{
foreach ($numbers as $number) {
if ($number % 2 === 0) {
yield $number;
}
}
}
foreach (filterEven(rangeGenerator(1, 10)) as $num) {
echo $num . ' '; // 2 4 6 8 10
}Generator 作为 iterable
php
<?php
declare(strict_types=1);
function fibonacci(int $max): iterable
{
$a = 0;
$b = 1;
while ($a <= $max) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
foreach (fibonacci(100) as $num) {
echo $num . ' ';
}
// 0 1 1 2 3 5 8 13 21 34 55 89详细说明
iterable vs array
php
<?php
declare(strict_types=1);
// 不确定参数是数组还是 Generator 时使用 iterable
function process(iterable $data): void { }
// 明确参数是数组时使用 array(更具体)
function processArray(array $data): void { }实战示例
通用集合管道
php
<?php
declare(strict_types=1);
class Pipeline
{
public static function from(iterable $source): self
{
return new self($source);
}
private function __construct(private readonly iterable $source) {}
public function map(callable $fn): self
{
$gen = (function () {
foreach ($this->source as $k => $v) {
yield $k => $fn($v);
}
})();
return new self($gen);
}
public function filter(callable $fn): self
{
$gen = (function () {
foreach ($this->source as $k => $v) {
if ($fn($v)) yield $k => $v;
}
})();
return new self($gen);
}
public function toArray(): array
{
return iterator_to_array($this->source);
}
}
$result = Pipeline::from(range(1, 100))
->filter(fn($n) => $n % 2 === 0)
->map(fn($n) => $n ** 2)
->toArray();
echo implode(', ', array_slice($result, 0, 5)); // 4, 16, 36, 64, 100注意事项
1. iterable 不能用于属性声明
php
// public iterable $items; // 错误!2. iterable 不能实例化
php
// new iterable(); // 错误!最佳实践
- API 接口用 iterable:不确定数据来源时
- 内部实现用 Generator:惰性求值节省内存
- 明确来源用 array:已知是数组时使用具体类型
- 链式管道:使用 iterable 实现惰性数据处理
下一节
下一节将简要介绍 enum 枚举类型。
进阶用法
调试与测试技巧
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');