If you include a file in PHP within a loop will it

2020-02-14 19:42发布

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?

3条回答
Bombasti
2楼-- · 2020-02-14 20:24

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:

<?php 

echo 'hello from version 1.0';
sleep(10);

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.

查看更多
够拽才男人
3楼-- · 2020-02-14 20:35

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

查看更多
做自己的国王
4楼-- · 2020-02-14 20:45

It will include the file ten times.

If that's a problem, you could use include_once

查看更多
登录 后发表回答