require is similar to
include, except that it will produce a fatal
E_COMPILE_ERROR level error on failure. When the
require fails, it will halt the script. When the
include fails, it will not halt the script and only emit
include statement includes and evaluates a file.
$a = 'Hello World!';
include 'variables.php'; echo $a; // Output: `Hello World!`
Be careful with this approach, since it is considered a code smell, because the included file is altering amount and content of the defined variables in the given scope.
You can also
include file, which returns a value. This is extremely useful for handling configuration arrays:
<?php return [ 'dbname' => 'my db', 'user' => 'admin', 'pass' => 'password', ];
<?php $config = include 'configuration.php';
This approach will prevent the included file from polluting your current scope with changed or added variables.
include & require can also be used to assign values to a variable when returned something by file.
include1.php file :
<?php $a = "This is to be returned"; return $a; ?>
index.php file :
$value = include 'include1.php'; // Here, $value = "This is to be returned"