PHP includes and required
include_once in php, include php in html, php include not working, php include path, php include file path, include file from another folder
PHP has support for calling one script from another. Using a special language construct, you can call a script from a separate file by its name, just as functions are called by name. This ability is called file attachment. Moreover, such a file can be either a php script or any other text file. For example an HTML page.
Why split and include php scripts
PHP developers split all the source code of a project into separate scripts to make it easier to work with them. If you had to write all the code in one file, then such a scenario would become simply immense and it would be absolutely impossible to navigate there. So splitting your code into different scenarios is a natural way to deal with complexity.
There is one more positive effect of such division. If you move the repeating blocks of code into separate scripts, you will be able to reuse one code in different files and include it only on demand. Custom functions are a good example. It is very convenient to declare them in a separate script, and then include them where these functions are needed.
File connection methods
There are two language constructs to include files in PHP:
require_once. How are they different? In fact, the differences between the two are minimal. Both of these keywords include a file with the specified name and throw an error if the given file does not exist.
However, the peculiarity of the work
require_onceis that the file will be included only once, even if this instruction is called several times with the same file name.
File connection examples
First, let's see how easy it is to connect one script inside another. To do this, we will use the instructions
require. Let's say we have two scenarios:
A relative path contains an address only relative to the current working directory. So if the script is in a folder
/var/www/web/site, then you can use the following path to connect the file:
Always prefer to specify relative paths so that the site continues to work if it is moved to another folder.
PHP has useful built-in constants that come in handy for use in include file paths.
__DIR__- Full path to the directory where the current script
__FILE__is located - Full path to the current script
Variable visibility in pluggable scripts
It should be remembered that since connecting files is just gluing them into one, then all variables in different scenarios also receive a common scope.
PHP does not have a module system that exists in other programming languages (Python, Java, ECMAScript 6). It is not possible to "import" only individual variables or functions from a pluggable script.
It also follows from this that if you connect the same script twice, then the variables and functions from it will also be declared again, and this may cause an error. So use
require_onceit to prevent this from happening.