include require

suggest change

require

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 E_WARNING.

require 'file.php';

PHP Manual - Control Structures - Require

include

The include statement includes and evaluates a file.

./variables.php
$a = 'Hello World!';
./main.php`
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:

configuration.php
<?php 
return [
    'dbname' => 'my db',
    'user' => 'admin',
    'pass' => 'password',
];
main.php
<?php
$config = include 'configuration.php';

This approach will prevent the included file from polluting your current scope with changed or added variables.

PHP Manual - Control Structures - Include


include & require can also be used to assign values to a variable when returned something by file.

Example :

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"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Control structures:
* goto
* while
* include require
* return
* for
* if
* switch

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
42 Control structures
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR