PHP include file - Include files only once

Home - Tutorials - Basics

In this tutorial I will show you how to divide your code into more files and how to include various files into your actual PHP code.

Tutorial info:

Name:PHP include file
Total steps:5

Bookmark PHP include file

Step 5 - Include files only once

PHP include file

In a big and complaex project it can happen that you don't know whether a file was included yet or not. For example suppose the following situation:

In this case you can not be sure that C.php is surely included in A.php besides this you want to avoid duplicated includes. To solve this problem you can use the include_once or the require_once functions.

These functions first checks whether a file was included or not. After this check they include the file only if it was not included before. To demonstarte this let's go back to an older example and now use include_once instead of include as follows:
  1. <?php
  2. include_once ('internal.php');
  3. echo "Multiple include test.<br/>";
  4. include_once ('internal.php');
  5. echo "Now include it again.<br/>";
  6. include_once ('internal.php');
  7. echo "Multiple include test.<br/>";
  8. include_once ('internal.php');
  9. ?>
So the code is very similar but the output is rather different:
-->internal.php<-- Multiple include test. Now include it again. Multiple include test.  

Previous Step of PHP include file

Tags: php incluude file, php include, include file, file include, php, include, file

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1448