Which method shall you use between include() or include_once() and require() or require_once () ?

include once vs. require once
include once vs. require once

To include a file in your php script, you will need to use any of the following function:
a. include()
b. include_once()
c. require()
d. require_once ()

It is a multiple answer choice question where all choices are close to correct answer. Any one of the above functions will do the job that is to include a file. So which one is best option?

In this situation, I remember the time when I was preparing for my under-graduation admission tests. The questions were MCQ and we used to choose the best answer by eliminating the wrong answers. Lets apply the same trick here also.

The difference between include()/require() and include_once()/require_once() is that latter ones will check whether the mentioned file was included earlier. Now, as including a file more than once will repeat the execution and thus will cause significant failure of your application, you should always consider using any of include_once() or require_once() methods.

Another reason to use one of the _once() methods is because they are faster in performance. See the _once() methods performance tests results here.

We eradicated two options at once!

Now let us see what is the conflict between include() and require() methods. In recent versions of PHP, the only difference between require() (or require_once()) and include() (or include_once()) is in the fact that, while the latter will only throw a warning and allow the script to continue its execution if the include file is not found, the former will throw an error and halt the script.

So as you know what they do, depending on your requirement you will use either include_once() or require_once().

For me, I will use require_once() because I prefer to get fatal error during development instead of getting warnings at production level. What about you?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.