为了最大限度地减少页面加载时间,我们将 PHP 生成的 HTML 缓存为 HTML 文件。如果存在“缓存文件”,我们将使用它。否则,我们运行 PHP 脚本来生成页面。
为了进一步降低页面加载速度,我们想删除“如果文件存在”行(这需要时间),如果文件不存在,则让 PHP 生成错误。然后我们将“捕捉”错误并让 PHP 生成页面。
问题如下:是否有一种简单的方法可以在 PHP 中实现“出错时离开功能”。
这是我们的代码:
function UseCachedPage()
{
$CacheFile='mypage.html';
if(!file_exists($CacheFile)) return; //Would like to skip this to save time
include($CacheFile);
//Magic "on error, leave function" needed here.
exit; //Cache included, so no need to run the php.
}
任何帮助,将不胜感激。
最佳答案
根据docs :
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.
所以这意味着如果你想“捕获”它,你必须使用
require
反而。现在,你只能捕捉到这个 fatal error as of PHP 7 , 这一点很重要。function UseCachedPage() {
$CacheFile = "mypage.html";
try {
require($CacheFile);
exit;
} catch (Error $e) {
// Call something to build your file here
}
}
关于php - PHP中有没有办法让函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58838392/