"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."


Click Above to BOOK HOTEL NOW!

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.php
echo "<h1>Welcome to My Website</h1>";
?>

<?php
// index.php
include "header.php";
echo "<p>This is the home page.</p>";
?>

Output:

Welcome to My Website
This is the home page.

Using require

Example:

<?php
// config.php
$siteName = "My PHP Blog";
?>
 
<?php
// about.php
require "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:

<?php
include_once "config.php";
require_once "header.php";
?>

 

 

Click Below to Shop Now at AMAZON

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)