Caching includes in PHP for iterated reuse

╄→尐↘猪︶ㄣ 提交于 2019-12-06 04:14:23

This would only make any sense if the include file was accessed across a network.

There is no inherit caching functionality I've missed, is there?

All operating systems are very highly optimized to reduce the amount of physical I/O and to speed up file operations. On a properly configured system in most cases, the system will rarely revert to disk to fetch PHP code. Sit down with a spreadsheet and have a think about how long it would take to process PHP code if every file had to be fetched from disk - it'd be ridiculous, e.g. suppose your script is in /var/www/htdocs/index.php and includes /usr/local/php/resource.inc.php - that's 8 seek operations to just locate the files - @8ms each, that's 64ms to find the files! Run some timings on your test case - you'll see that its running much, much faster than that.

As with Sabeen Malik's answer you could capture the output of the include with output buffering, then concat all of them together, then save that to a file and include the one file each time.

This one collective include could be kept for an hour by checking the file's mod time and then rewriting and re including the includes only once an hour.

I think better design would be something like this:

// rand.php
function get_rand() {
    return rand(0, 999);
}

// index.php
$file = 'rand.php';
include($file);

while($i++ < 1000){
    echo get_rand();
}
David Lozano

Another option:

while($i++ < 1000) echo rand(0, 999);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!