Include files in php using include, include_once, require or require_once
Include files in php using include, include_once, require or require_once
The Core PHP Constructs for Including Files
There are four core constructs for including files into your PHP scripts. The main objective is for you to create code in separate files and then be able to use that code to include functions, variables and etc, in other PHP scripts. You have two main options. To include() a file or to require() a file. We’ll get into the specifics in a moment and you’ll quickly understand what the differences are.
The include() Construct
The include() constrcut is the most commonly used method to include files amongst most developers. It’s purpose is to simply include a file and that’s it. If the file does not exist, it will return a warning and still allow the script that’s trying to include the file to continue to operate even if the warning is issued. Here’s a common example:
PHP Example:
Now, all of the code, and functions from get.php will be available throughout the rest of the current PHP script for use with the rest of your code.
The include_once() Construct
Ok, the main difference between the include_once() construct and the include() construct is that if the file has already been included in this code execution, it will not be included again. This is a good method to use and I would recommend it above using the standard include() construct because it can prevent you from redeclaring functions that you may have already included previously. As your code becomes more complex, you may have files included in different files and when calling those files, you may start running into problems.
PHP Example:
The require() Construct
The require() construct is the same as include, but one major difference. If the file does not exist, or cannot be included, a Fatal Error will be produced and the execution of the PHP script will be halted! This construct is important for those applications you may develop that have dependancies from other files which must be met in order for your script to function properly.
PHP Example:
The require_once() Construct
This construct is the one that I use more than the other three. Personally, I feel that this construct takes into account all of the necessary reasons you would be including a file in the first place. Just like include_once() the require_once() construct determines if the file has already been included and if it has been, it will skip this instance. In addition, a Fatal Error will be produced just like the require() construct does if the file cannot be read or included.
PHP Example:
Thanks Phphelper
Include files in php using include, include_once, require or require_once,