php - PHP中有没有办法让函数出错

标签 php caching error-handling

为了最大限度地减少页面加载时间,我们将 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/

相关文章:

algorithm - 我应该启动错误还是更正值

php - 从每个数组中回显特定行

php - 如何在单个查询中查询 3 个表?

javascript - 使用 :eq() Selector 时字符串丢失

javascript - 获取相关的js文件 : What is the point of adding ? t=B48E5AB

c++ - 错误: no match for ‘operator>>’ for my class

powershell - 我在PowerShell脚本中放置陷阱{}的位置是否重要

php - 如何使用 Laravel 查询生成器执行此查询

caching - 如何在 Grails 1.2.5 上清除 Ivy 缓存

Node.js 集群共享缓存