PHP clearstatcache 函数
最后修改于 2025 年 4 月 3 日
PHP 的 clearstatcache
函数用于清除文件状态缓存。PHP 缓存文件信息以提高性能。
基本定义
clearstatcache
函数清除文件系统函数的缓存结果。它接受可选参数以清除特定文件。
语法:clearstatcache(bool $clear_realpath_cache = false, string $filename = ""): void
。此函数影响所有文件系统函数。
clearstatcache 基本示例
这展示了 clearstatcache
的最简单用法,用于清除所有缓存数据。
basic_clearstatcache.php
<?php declare(strict_types=1); $file = 'test.txt'; // First check $size1 = filesize($file); // Modify file file_put_contents($file, 'New content'); // Clear cache clearstatcache(); // Second check $size2 = filesize($file); echo "Before: $size1, After: $size2";
这演示了在不清除缓存的情况下,文件大小可能被缓存的情况。第二个 filesize
调用返回更新后的数据。
清除特定文件缓存
您可以清除特定文件的缓存以提高性能。
specific_file.php
<?php declare(strict_types=1); $file1 = 'file1.txt'; $file2 = 'file2.txt'; // Check both files $size1a = filesize($file1); $size2a = filesize($file2); // Modify file1 file_put_contents($file1, 'Updated'); // Clear cache only for file1 clearstatcache(true, $file1); // Check again $size1b = filesize($file1); $size2b = filesize($file2); echo "File1: $size1a → $size1b, File2: $size2a → $size2b";
这仅清除 file1.txt
的缓存,保留 file2.txt
的缓存。这比清除所有缓存更有效。
Realpath 缓存清除
该函数还可以清除符号链接的 realpath 缓存。
realpath_cache.php
<?php declare(strict_types=1); $link = 'symlink_to_file'; // Get real path (cached) $path1 = realpath($link); // Change symlink target unlink($link); symlink('new_target.txt', $link); // Clear realpath cache clearstatcache(true); // Get updated real path $path2 = realpath($link); echo "Before: $path1, After: $path2";
这展示了在使用符号链接时如何清除 realpath 缓存。第一个参数必须为 true 才能清除此缓存。
性能影响示例
这演示了过度清除缓存对性能的影响。
performance.php
<?php declare(strict_types=1); $file = 'large_file.txt'; $iterations = 1000; // With cache clearing $start1 = microtime(true); for ($i = 0; $i < $iterations; $i++) { clearstatcache(); filesize($file); } $time1 = microtime(true) - $start1; // Without cache clearing $start2 = microtime(true); for ($i = 0; $i < $iterations; $i++) { filesize($file); } $time2 = microtime(true) - $start2; echo "With clearing: $time1, Without: $time2";
这显示了不必要地清除缓存时显着的性能差异。只有在预期文件更改时才清除缓存。
与 file_exists 结合使用
此示例演示了 clearstatcache
与 file_exists
一起使用。
file_exists.php
<?php declare(strict_types=1); $file = 'temp_file.txt'; // Create file file_put_contents($file, 'data'); // Check exists (cached) $exists1 = file_exists($file); // Delete file unlink($file); // Check without clearing cache $exists2 = file_exists($file); // Clear cache and check clearstatcache(); $exists3 = file_exists($file); echo "Exists: $exists1, Deleted (cached): $exists2, Deleted (cleared): $exists3";
这演示了如何缓存 file_exists
的结果。在清除缓存之前,第二次检查返回错误数据。
最佳实践
- 选择性清除: 仅清除已更改文件的缓存。
- 性能: 避免在循环中不必要地清除缓存。
- Realpath: 使用第一个参数来处理符号链接的更改。
- 测试: 在您的特定环境中验证行为。
来源
本教程介绍了 PHP 的 clearstatcache
函数,并提供了在不同场景中显示其用法的实际示例。
作者
列出 所有 PHP 文件系统函数。