How are include_once loops handled in php?

332 views Asked by At

I have 3 different files-

  1. fileMainIncludeEverywhere.php

    ...
    include_once('fileMinorInclude.php');
    ?>
    
  2. fileMinorInclude.php

    ...
    include_once('fileMainIncludeEverywhere.php');
    ...
    
  3. fileToRun.php

    ...
    include_once('fileMainIncludeEverywhere.php');
    ...
    

I have a lot of files like fileToRun.php.

Currently I'm not facing any errors in my code, but I want to know if there's any case where this would fail?

2

There are 2 answers

1
d.coder On BEST ANSWER

I think no error in this case. Because include_once will only load the file for the first time then upcoming load request will be rejected for the same file.

So from your example:

  1. fileToRun.php will load fileMainIncludeEverywhere.php (first call)
  2. fileMainIncludeEverywhere.php will load fileMinorInclude.php (first call)
  3. fileMinorInclude.php will call to load fileMainIncludeEverywhere.php but it will be rejected as it has been already loaded in first step.

Hope it will help.

1
spinkus On

include_once:

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once.

Here "code from a file" also entails the executed PHP file.

Note it's generally best practice to use require_once() instead of include_once() unless you've got a specific reason for using include_once() (like say including optional template components). This because require_once() will terminate (fail fast) if the required resource is not found, and not finding it normally should be a terminal failure.