Include, include_once vs. Require and require_once in PHP


These four functions are used to add a PHP script file in another. This allows you to break your script into several files instead of having a single long file. You could have a file called functions.php with your user defined functions. Then include it in your other files to use those functions.

All four of them behave differently. Let us take a look at how they work.

Include

Includes and evaluates a file. If the file is not present it gives a warning.

Example:
hello.php

world.php

world.php

If the file hello.php is not present

Note: The execution of the script continues even when hello.php is not present.

Require

This one also adds a file into the current script for execution. But upon failure to include the file i.e. when the file is not present, require will stop the execution of the script and produce an error.

Example:
hello.php

world.php

world.php

If the file hello.php is not present, nothing is printed from the script. An error message will be displayed based on your configuration.

Include vs. Require

Include does not produce an error and continues the execution of the script. It only produces a warning. Require on the other hand, produces an error and halts the script execution.

Include_once and require_once

These two functions will include other PHP files for inclusion. If the file has been required or included before in the script, then it will not be included again. Otherwise the file will be added. Include and include_once are similar and require and require_once work similarly.

Example:
hello.php

world.php

world.php (If the file is present)

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers