Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Difference between require, include, require_once and include_once in PHP?

In PHP:

When should I use require vs. include?
When should I use require_once vs. include_once?
by

2 Answers

kshitijrana14
require vs. include*
The difference between include and require arises when the file being included cannot be found: include will emit a warning ( E_WARNING ) and the script will continue, whereas require will emit a fatal error ( E_COMPILE_ERROR ) and halt the script.

Use require when the file is required by the application.
Use include when the file is not required and application should continue when file is not found.


*require_once vs. include_once

include_once will throw a warning, but will not stop PHP from executing the rest of the script. require_once will throw an error and will stop PHP from executing the rest of the script.

The include_once keyword is used to embed PHP code from another file. If the file is not found, a warning is shown and the program continues to run. If the file was already included previously, this statement will not include it again.
The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.
Shahlar1vxp
Although both require* and *include* are ways to include files, but there is a major difference between *require* and *include*. While *require* means that it has its requirement or needs it, it has to be there whereas *include* means it is going to include a file but it is not necessary as a requirement. *Require_once* means that it requires it only once whereas *include_once means that it will include a file but only once. There is a short example showing how to write these functions:
require 'filename' 
require_once 'filename'
include 'filename'
include_once 'filename'
MounikaDasa
My suggestion is to just use require_once 99.9% of the time.

Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

If you are require/including code that executes on the spot, that's procedural code, and you need to get to know a new paradigm. Like object oriented programming, function-based programming, or functional programming.

If you're already doing OO or functional programming, using include_once is mostly going to be delaying where in the stack you find bugs/errors. Do you want to know that the function do_cool_stuff() is not available when you go to call for it later, or the moment that you expect it to be available by requiring the library? Generally, it's best to know immediately if something you need and expect isn't available, so just use require_once.

Login / Signup to Answer the Question.