Why include when you can require in PHP?

What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?


Sometimes you are including files from libraries that you do not control or your code is being run on different environments.

It is possible that some of these aren't actually required for your script but are helper files or extras.

For instance, if your PHP is generating HTML, you might use an include to add a banner. But you wouldn't want your file to halt if for some reason that banner file was missing. You'd want to gracefully fail instead.


The difference between include/include_once and require/require_once is that when a file is not found, the former triggers a warning whereas the latter triggers an error. Opinions may vary but IMO, if a needed file is not present or readable for some reason, this represents a very broken situation and I would rather see an error and halt execution, than have a warning and proceed execution in a clearly broken context. So I believe it to be best practice to use require/require_once exclusively and avoid include/include_once altogether.


include - this attempts to load a file but does not halt execution if it fails

include_once - does the same as 'include' but runs an additional check to make sure the file hasn't already been included in the current script

require - this attempts to load a file and throws a fatal error on failure

require_once - same as 'require' but runs an additional check to make sure it's loaded only once

If you don't need to use include_once or require_once try to avoid them since the extra check adds a little overhead.

EDIT: I should add that they key difference is that require fails at the compiler level, while include throws an error at run-time.


Require will stop the script if it can't include the file.
Include will just give an error message.

Btw.: *_once is slow. Shouldn't use it unless you really need to.