Welcome to my series on every PHP keyword and its usage. Today’s items:
These are all related calls that allow you to split up your PHP script into multiple, smaller files for easier comprehension and reuse.
When you include a file, that file will be compiled and run in the same scope, as if it was part of the same file, with a couple of caveats:
- The script still needs to start with
<?php, else it will output the file contents to the browser as plain HTML (which may be what you want).
- A script can return a value, which can be assigned from the
When you include a file, it will check for it in the following order:
- First, by iterating over each directory in the include path. It’s fine if you don’t know what this is, as it’s mostly used for server-wide packages.
- Second, by checking the working directory.
- When running on a server, this will be the directory that contains the script file that the user is currently visiting.
- When running from the command line, this will be the directory the user was in when they called the script.
- Finally, by checking the directory of the file that you are including another file from.
If the path to your included file starts with
../, the system will skip checking the include path, and just check the working directory and the script’s directory.
If you give it an absolute path starting with
/, the system will go specifically to that path.
As you may realise, using anything except an absolute path can lead to situations where the file you intended to include can be confused with a different file with a higher priority. As such, I’d recommend that you always use absolute paths, and use
__DIR__ to get the directory containing the current file.
If the file cannot be found, the system will emit a warning and keep going.
require construct works exactly the same way as
include, except that instead of emitting a warning if it can’t find the file, it will throw a fatal error.
Typically speaking, if one of your PHP files is missing, it’s probably best if your code exits, rather than trying to valiantly fight on while missing half its logic. As such,
require should be used in nearly all situations where you may be tempted to use
include_once and require_once
These two constructs work the same way as
require, respectively. Except that if the file has already been included, it won’t be included again.
The most common usage for these is when you are including files containing functions and classes, which will throw an error if you try to define them again.
Note that if a file has already been included,
require_once will simply return
true, no matter what the included file might return.
Author Callum Muir