PHP缓存包含文件

Pet*_*ter 3 php caching

我在test.php中有以下测试代码:

<?php
$step = $_GET['step'];
switch($step) {
  case 1:
    include 'foo.php';   # line 5
    file_put_contents('foo.php', '<?php print "bar\\n"; ?>');
    header('Location: test.php?step=2');
  break;
  case 2:
    print "step 2:\n";
    include 'foo.php';
  break;
}
?>
Run Code Online (Sandbox Code Playgroud)

foo.php最初有以下内容:

<?php print "foo\n"; ?>
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中调用test.php?step = 1时,我希望得到以下输出:

step 2:
bar
Run Code Online (Sandbox Code Playgroud)

但我得到这个输出:

step 2:
foo
Run Code Online (Sandbox Code Playgroud)

当我在第5行注释掉include时,我得到了理想的结果.结论是,PHP缓存了foo.php的内容.当我用step = 2重新加载页面时,我也得到了所需的结果.

现在......为什么这样以及如何避免这种情况?

小智 6

假设您使用OPcache,可以使用opcache.enable = 0.

一种更有效的方法是使用

opcache_invalidate ( string $script [, boolean $force = FALSE ] )
Run Code Online (Sandbox Code Playgroud)

这将从内存中删除脚本的缓存版本并强制PHP重新编译.


Mor*_*jad 5

请注意,这opcache_invalidate并不总是可用。所以最好检查一下是否存在。另外,您应该检查opcache_invalidateapc_compile_file

以下函数将完成所有操作:

    public static function clearCache($path){
        if (function_exists('opcache_invalidate') && strlen(ini_get("opcache.restrict_api")) < 1) {
            opcache_invalidate($path, true);
        } elseif (function_exists('apc_compile_file')) {
            apc_compile_file($path);
        }
    }
Run Code Online (Sandbox Code Playgroud)