ZetCode

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 结合使用

此示例演示了 clearstatcachefile_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 的结果。在清除缓存之前,第二次检查返回错误数据。

最佳实践

来源

PHP clearstatcache 文档

本教程介绍了 PHP 的 clearstatcache 函数,并提供了在不同场景中显示其用法的实际示例。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 PHP 文件系统函数