It's really easy to include files in PHP and when we progress in PHP, we try to keep our code clean and in separate files and execute it by including whenever necessary. We might keep a library of functions a=in a separate file and include it in the final script whenever required. We do that to reduce writing down same code again and again. We might use other programmers' code just by including their files as well. In all those scenarios, we need include or require statements to include files.
The include Statement
Using include we tell PHP to include the contents of a particular file and execute it if there is any code to execute. All it does is to include the contents of the file we are including and makes it a bigger script when it compiles the code.
//code inside PHP include "functions.php"; ... ... other code ...
This is really helpful statement as there is a bit of problem with include and this one solves it.
When we write include statement, PHP included the whole file. Let's understand by example:
//code inside PHP include "functions.php"; ... ... other code ... include "math.php"; //end
Let's assume we have functions in math.php as well. For example the content of the math.php:
//code inside PHP include "functions.php"; ... more code .. //end
Now we are including functions.php and math.php just once in some script. But math.php also has functions.php inside it. So, the script is going to include the functions.php one more time which is redundant code. It's already been included once.
To skip including files again and again we can use include_once and PHP will include that file just for one time and won't keep including it again and again.
PHP will ignore the code if it's included already if we have used included_once. To do that PHP compares the absolute file paths after all relative paths are resolved.
require and require_once
This statement encounters one more potential problem that include and include_once have.
If we use include or include_once, PHP will try to attempt the file and if it can't access it, it won't bother. It will keep executing the remaining code and will show the output. So, basically PHP will run the script even if the file is not found.
But what if we absolutely need that file or there won't be a meaningful output?
That's why we need require statement. When the file is required no matter what, use require to include the file. For example:
//code inside PHP require "functions.php"; require_once "math.php"; //end
If PHP can't find the required file then it will give a fatal error. In the case of include, it won't give you a fatal error.
differences file include