PHP include_once
Summary: in this tutorial, you will learn how to use the PHP include_once construct to include a file once.
Introduction to the PHP include_once construct
In the include tutorial, you learned how to load the code from another file using the include construct.
Sometimes, you may have a file that is included more than once.
If the included file has a function, you’ll get a fatal error because the function is already redeclared in the first load. For example:
Suppose that you have the following project directory:
.
├── inc
│ └── functions.php
└── index.phpCode language: plaintext (plaintext)
The functions.php has the dd() function definition:
function dd($data)
{
echo ‘<pre>’;
var_dump($data);
echo ‘</pre>’;
die();
}
Code language: HTML, XML (xml)
And in the index.php file, you include the functions.php file twice:
include ‘inc/functions.php’;
include ‘inc/functions.php’;
Code language: HTML, XML (xml)
PHP will issue the following error if you run the index.php file:
Fatal error: Cannot redeclare dd() (previously declared in .\inc\functions.php:3) in .\inc\functions.php on line 3Code language: plaintext (plaintext)
Likewise, if the included file outputs some HTML elements, you’ll see them more once on the page. To see how it happens, let’s create two new files header.php and footer.php in the inc directory:
header.php
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PHP include_once</title>
</head>
<body>Code language: HTML, XML (xml)
footer.php
</body>
</html>Code language: HTML, XML (xml)
In the index.php file, if you include the header.php file twice, you’ll see that the page will have two headers:
include 'inc/header.php'
include 'inc/header.php' <h1>PHP include_once Demo</h1> include ‘inc/footer.php’
Code language: HTML, XML (xml)
To avoid including a file more than once, you can use the include_once statement:
include_once 'path_to_file';Code language: PHP (php)
The include_once behaves like the include statement except that if the file is included again, the include_once won’t load the file and returns true.
Simply put, the include_once loads the file just once regardless of how many times the file is included.
In the example above, if you use the include_once construct, the script will work properly:
include_once 'inc/header.php'
include_once 'inc/header.php' <h1>PHP include_once Demo</h1> include_once ‘inc/footer.php’
Code language: HTML, XML (xml)
Why use the PHP include_once construct
Image that you have a file called index.php that loads two other files:
- Logger.php
- Database.php
The Database.php file also loads the Logger.php file. In this case, the Logger.php file is used twice, once in the Database.php file and another in the index.php.
In this case, you need to use the include_once construct to load the Logger.php file to make it work properly.
Summary
- Use the PHP
include_oncestatement to load a file once.