PHP realpath_cache_get 函数
最后修改于 2025 年 4 月 3 日
PHP 的 realpath_cache_get
函数检索当前的 realpath 缓存条目。它有助于理解 PHP 如何缓存已解析的文件路径。
基本定义
realpath_cache_get
函数返回一个缓存的 realpath 条目数组。PHP 使用此缓存来存储已解析的路径以提高性能。
语法: realpath_cache_get(): array
。该函数不接受任何参数,并返回一个包含缓存条目的关联数组。
基本的 realpath_cache_get 示例
这展示了 realpath_cache_get
最简单的用法,用于查看缓存。
basic_realpath_cache.php
<?php declare(strict_types=1); // Access a file to populate the cache $path = realpath(__FILE__); // Get the cache contents $cache = realpath_cache_get(); print_r($cache);
这将输出解析当前文件路径后的 realpath 缓存。缓存包含已解析路径的详细信息。
缓存条目结构
每个缓存条目包含几个字段,提供有关路径的信息。
cache_structure.php
<?php declare(strict_types=1); // Access a file to populate the cache $path = realpath(__DIR__ . '/../config.ini'); // Get and examine a cache entry $cache = realpath_cache_get(); $entry = current($cache); echo "Key: " . key($cache) . "\n"; echo "Resolved path: " . $entry['realpath'] . "\n"; echo "Expire time: " . $entry['expires'] . "\n"; echo "Is directory: " . ($entry['is_dir'] ? 'Yes' : 'No') . "\n";
这展示了缓存条目的结构。每个条目包括已解析的路径、过期时间以及它是否为目录。
监控缓存大小
您可以查看 realpath 缓存中有多少条目。
cache_size.php
<?php declare(strict_types=1); // Access several files to populate cache realpath(__FILE__); realpath(__DIR__); realpath('/tmp'); // Get cache information $cache = realpath_cache_get(); echo "Cache contains " . count($cache) . " entries\n"; echo "Memory usage: " . memory_get_usage(true) . " bytes\n";
这演示了如何查看缓存大小及其对内存的影响。随着脚本执行过程中解析的路径越来越多,缓存也会随之增长。
缓存过期
缓存条目根据 realpath_cache_ttl 设置具有过期时间。
cache_expiration.php
<?php declare(strict_types=1); // Get current time $now = time(); // Access a file $path = realpath(__FILE__); // Check cache expiration $cache = realpath_cache_get(); $entry = current($cache); $remaining = $entry['expires'] - $now; echo "Cache entry expires in $remaining seconds\n";
这计算了一个缓存条目将在多长时间后过期。默认的 TTL 通常是 120 秒,但可以在 php.ini 中更改。
比较缓存和未缓存的性能
缓存显著提高了重复路径解析的性能。
performance_comparison.php
<?php declare(strict_types=1); function timeResolution(string $path): float { $start = microtime(true); realpath($path); return microtime(true) - $start; } $path = __FILE__; // First resolution (uncached) $uncachedTime = timeResolution($path); // Second resolution (cached) $cachedTime = timeResolution($path); echo "Uncached: " . $uncachedTime . " seconds\n"; echo "Cached: " . $cachedTime . " seconds\n"; echo "Improvement: " . ($uncachedTime/$cachedTime) . "x faster\n";
这比较了缓存与未缓存的路径解析的性能。realpath 缓存可以使重复操作显著加快。
最佳实践
- 监控大小:在长期运行的脚本中关注缓存大小。
- TTL 设置:根据需要调整 realpath_cache_ttl。
- 调试:用于调试路径解析问题。
- 性能:了解它对文件系统操作的影响。
来源
本教程通过实际示例介绍了 PHP 的 realpath_cache_get
函数,展示了其在不同场景下的用法。
作者
列出 所有 PHP 文件系统函数。