If you include a file in PHP within a loop will it access the file every time it runs in the loop?

前端 未结 3 1186
暖寄归人
暖寄归人 2020-12-21 13:34

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 th

相关标签:
3条回答
  • 2020-12-21 13:55

    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

    0 讨论(0)
  • 2020-12-21 13:58

    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.

    0 讨论(0)
  • 2020-12-21 13:59

    It will include the file ten times.

    If that's a problem, you could use include_once

    0 讨论(0)
提交回复
热议问题