如果在循环中包含 PHP 中的文件,每次在循环中运行时它都会访问该文件吗?
如果你有这个,
for($i = 0; $i < 10; $i++) include('whatever.php');
它会实际提取文件十次,还是只会访问该文件一次,并保留其内容并简单地评估其他 9 次?
If you have this
for($i = 0; $i < 10; $i++) include('whatever.php');
Will it pull the file ten actual times, or will it only access the file once, and keep its contents and simply evaluate it for the other 9 times?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很简单,可以检查 - 将 sleep() 放在那里,让文件执行一些输出,然后在其中一个睡眠期间,修改文件以更改其输出。
whatever.php:
然后在其中一个睡眠期间,使用另一个 shell 将其更改为“版本 2.0”。如果输出没有改变,那么 PHP 已经加载了一次文件并缓存了它 - 您仍然会获得文件输出/效果的 10 个副本,但您会知道 PHP 没有访问磁盘 10 次。
Simple enough to check - put a sleep() in there, have the file do some output, and during one of the sleep periods, modify the file to change its output.
whatever.php:
then during one of the sleeps, change it to "version 2.0" using another shell. If the output doesn't change, then PHP has loaded the file ONCE and cached it - you'll still get 10 copies of the file's output/effects, but you'll know that PHP didn't hit the disk 10 times.
如果您询问该文件是否将被兑现并从内存中包含,而不是一次又一次地解析并编译为 PHP 字节码: - 是的,如果您包含给定文件 n 次,您将处理同一文件 n 次。这是标准的 PHP 行为,但是...
您可以更改它(在我看来,您正在寻找它?)。正如我所说,PHP 将在第一次包含该文件,并且不会为您缓存它...除非您使用 APC 等任何 PHP 缓存模块:
当使用 APC,事情会有所不同,输出的结果将是相同的,但服务器行为会改变很多!第一次包含文件时,它将被解析、编译为 PHP 字节码(机器可读指令)并存储在共享内存中。稍后,除非给定的文件被修改,否则它将不会再次被处理! PHP 将直接进入您程序的预编译版本并执行它,为您节省大量时间和资源!适合高流量 Web 应用程序。
有关 APC 的更多信息此处
If you're asking if the file is going to be cashed and included from memory instead of parsed and compiled to PHP bytecode again and again: -Yes, you will process the same file n times if you include that given file n times. This is the standard PHP behavior but...
You can change that (and it seems to me that you're looking for that?). As I said, PHP will include the file the first time and will not cache it for you... unless you're using any PHP caching module like APC:
When using APC, things are going to be different, the outputted result will be the same but the server behavior will change a lot! The first time you include a file it will be parsed, compiled into PHP bytecode (machine readable instructions) and will get stored in a shared memory. Later, unless that given file gets modified, it will NOT be processed again! PHP will go straight to the pre-compiled version of your program and execute it, saving you a lot of time and resources! Good for high traffic web applications.
More about APC here
它将包含该文件十次。
如果这是一个问题,您可以使用
include_once
It will include the file ten times.
If that's a problem, you could use
include_once