We all know both the functions include and include_once in PHP will insert the content of the PHP file into another PHP file. Sometimes people may ask the difference especially in Interviews, you may have confused how to explain the difference between them.
Just reading a description without doing a practical experiment will not help in this case. So it is always better to do an experiment to understand it fully.
Lets begin the test:
There are two files we are going to use:
1. functions.php
1 2 3 4 5 |
<?php function some_function(){ echo 'functions.php is called'; } ?> |
2. index.php
1 2 3 4 5 6 7 8 |
<?php include('functions.php'); include('functions.php'); some_function(); ?> |
In index.php I have included the functions.php twice, what would be the result you think??
The result is a Fatal Error, something like this,
1 |
Fatal error: Cannot redeclare some_function() (previously declared in C:\xampp\htdocs\blog\include\functions.php:3) in C:\xampp\htdocs\blog\include\functions.php on line 4 |
How do you fix this now?
Fix this by using include_once() instead of include().
index.php (modified)
1 2 3 4 5 6 7 8 |
<?php include_once('functions.php'); include_once('functions.php'); some_function(); ?> |
Now you can see the output without any fatal error.
So, basically include_once checks if the file is already loaded, if loaded then it won’t load.