Alex Rivera | Logout

Difference between require, include, require_once and include_once?

Asked 2010-03-10T16:13:25.127
1452

In PHP:

  • When should I use require vs. include?
  • When should I use require_once vs. include_once?
Edit
Report

3 Answers

39

include() will throw a warning if it can't include the file, but the rest of the script will run.

require() will throw an E_COMPILE_ERROR and halt the script if it can't include the file.

The include_once() and require_once() functions will not include the file a second time if it has already been included.

See the following documentation pages:

answered 2011-11-03T11:48:14.713
16

The difference is in the error the commands generate. With require, the file you want to use is really required and thus generates an E_ERROR if it is not found.

require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error.

include only generates an E_WARNING error if it fails which is more or less silent.

So use it if the file is required to make the remaining code work and you want the script to fail the file is not available.


For *_once():

include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

Same applies to require_once() of course.


Reference: require(), include_once()

answered 2010-03-10T16:20:32.290
9

With require the file must exist, if it doesn't then an error will display; whereas with include - if the file doesn't exist then then the page will continue loading.

answered 2010-03-10T16:24:59.910

Your Answer