PHP include_once
The include_once
statement in PHP is used to include a PHP file in another PHP file. This statement includes and evaluates the specified file only once in a PHP script, i.e., if the file is included more than once, only the first included file will be processed, and subsequent inclusions will be ignored.
Syntax
The basic syntax of the include_once
statement is as follows:
include_once "filename.php";
Example
Suppose we have two PHP files named header.php
and footer.php
. We can include these files in our main PHP file using the include_once
statement as follows:
<!DOCTYPE html>
<html>
<head>
<title>PHP include_once</title>
</head>
<body>
<?php include_once "header.php"; ?>
<!-- html content goes here -->
<?php include_once "footer.php"; ?>
</body>
</html>
Output
The include_once
statement does not produce any output by itself. It simply includes the specified file in the current PHP file.
Explanation
The include_once
statement includes and evaluates the specified file during the execution of the PHP script. The included file is evaluated as if it were part of the calling file. The difference between include_once
and include
is that include_once
includes the file only once, whereas include
includes the file every time it is encountered in the script.
Use
The include_once
statement is useful when we have PHP code that is commonly used across multiple pages in a website. We can define this code in a separate file and use the include_once
statement to include it in all the pages that require it. This makes our code more modular and easier to maintain.
Important Points
- The
include_once
statement includes the specified file only once in a PHP script. - If the file has already been included, it will not be processed again.
- If the file cannot be found or there is an error in the included file, the PHP script will continue to execute, but a warning message will be issued.
Summary
The include_once
statement in PHP is used to include a PHP file in another PHP file. It includes and evaluates the specified file only once in a PHP script, making it useful for including code that is commonly used across multiple pages in a website. It is important to note that if the included file has errors, the PHP script will continue to execute, but a warning message will be issued.