Difference Between 'include' and 'require' Statements in PHP

I was asked the other day what’s the difference between include and require in PHP. They seemingly function the same but there is a significant difference.

First up, neither include or require are functions, they are constructs. It is therefore not necessary to call them using parentheses like include('file.php'); instead it is prefered to use include 'file.php'.

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. If the file being included is critical to the rest of the script running correctly then you need to use require.

You should pickup on any fatal errors thrown by require during the development process and be able to resolve them before releasing your script into the wild; however, you may want to consider using include to put in place a plan B if it’s not that straight-forward:-

if (@include 'file.php') {
	// Plan A
} else {
	// Plan B - for when 'file.php' cannot be included

In this example include is used to grab ‘file.php’, but if this fails we surpress the warning using @ and execute some alternative code. include will return false if the file cannot be found.

include_once and require_once behave like include and require respectively, except they will only include the file if it has not already been included. Otherwise, they throw the same sort of errors.

So to summarize include throws a warning and require throws a fatal error and ends the script when a file cannot be found. Simple as that!

Related Content

Published on