Difference between require, include, require_once and include_once?

In PHP, require and include are two statements that are used to include a file in a PHP script. The main difference between them is how they handle failures. If the file specified in the require statement cannot be included, it will cause a fatal error and stop the script from executing. On the other hand, if the file specified in the include statement cannot be included, it will only emit a warning and the script will continue to execute.

Both require_once and include_once work similarly to require and include, respectively, with the added benefit of checking if the file has already been included before attempting to include it. This can be useful to prevent multiple copies of the same file from being included, which can cause problems such as function redefinition errors.

Watch a course Learn object oriented PHP

So to summarize:

  • require includes and evaluates a specified file, and causes a fatal error if the file cannot be included.
  • include includes and evaluates a specified file, and only emits a warning if the file cannot be included.
  • require_once works like require, but it will only include the file if it has not been included before.
  • include_once works like include, but it will only include the file if it has not been included before.