The include_once () statement includes and evaluates the specified file during script execution. This behavior is similar to the include () statement, with the only difference being that if the code from the file is already included, it will no longer be included. As the name implies, it will be enabled only once. For example, I have three files,
FILES:
- functions.php
- GLOBALS.PHP
- header.php
Here's what each file looks like:
FUNCTIONS.PHP
<?php function foo(){ echo 'some code'; } ?>
GLOBALS.PHP:
<?php include('FUNCTIONS.PHP'); foo(); ?>
HEADER.PHP
<?php include('FUNCTIONS.PHP'); include('GLOBALS.PHP'); foo(); ?>
Now, if you try to open HEADER.PHP, you will receive an error message because GLOBALS.PHP already contains FUNCTIONS.PHP. You will receive a message stating that the function foo () has already been declared in GLOBALS.PHP and is also included in HEADER.PHP, which means that I turned on FUNCTIONS.PHP twice. Therefore, to enable only FUNCTIONS.PHP only once, I have to use the include_once () function, so my HEADER.PHP should look like this: HEADER.PHP
<?php include_once('FUNCTIONS.PHP'); include('GLOBALS.PHP'); ?>
Now when I open HEADER.PHP, I will no longer get the error, because PHP knows that including the FUNCTIONS.PHP file is ONCE only. Therefore, to avoid getting the error, it would be safe to use include_once () instead of the include () function in your PHP code.
source share