Include and Require (Code Reusability)
In PHP, the include
and require
statements are used to insert the content of one PHP file into another before
the server executes it. This is a great way to reuse code and keep projects
organized. Commonly, they are used for headers, footers, navigation menus, and
configuration files.
Difference
Between include
and require
·
include: If
the file is missing, PHP will display a warning but continue executing the
script.
·
require: If
the file is missing, PHP will throw a fatal error and stop script execution.
Using include
Example:
<?php// header.phpecho "<h1>Welcome to My Website</h1>";?><?php// index.phpinclude "header.php";echo "<p>This is the home page.</p>";?>
Output:
Welcome to My WebsiteThis is the home page.
Using require
Example:
<?php// config.php$siteName = "My PHP Blog";?> <?php// about.phprequire "config.php";echo "<h1>About Us - $siteName</h1>";?>
If config.php is missing:
·
include → Shows a
warning and continues.
·
require → Shows a
fatal error and stops.
include_once
and require_once
To avoid accidentally including the same file
multiple times (which can cause errors), PHP provides:
·
include_once
— Same as include,
but prevents multiple inclusions.
·
require_once
— Same as require,
but prevents multiple inclusions.
Example:
<?phpinclude_once "config.php";require_once "header.php";?>