Thursday, July 5, 2012

Including php files

Let's say that you have some functions that you want to use for a project of yours. If you copy paste the functions in all files where you need then when you want to change the way a function work you need to change it in all places. This changes are a lost of time and you will surely not modify it in all files so bugs may appear. The solution is to include php files using include and require methods that PHP provides us.

Using include

You can include a file like this:
include "functions.php"
Using this statement requires that the file functions.php must be in the same folder with the file in which you are including your functions. You can use relative or full path to the file like this:

include "usr/local/apache/htdocs/includes/functions.php"
For Unix/Linux/Mac path

For Windows the include statement might look like this:
include "c:\phpfunctions\functions.php"

The problem with include is that every time the PHP processor finds an include statement is that it will load the file in again. This takes up more memory than is necessary and is slow and inefficient. The other problem is that loading the file again will make functions to be redefined, which is not allowed, and will generate an error message.

Using include_once

If you are using include_once then the processor will check if the file is not already loaded and it will load it if it is not loaded. You can use it like this:
include_once "functions.php"

The problems with include and include_once is that if the file does not exist then the command will simply get ignored. Maybe some of those functions are needed for the website to work then you will get a lot of errors, maybe some errors like function not found. The solution is the require command.

Using require

require "functions.php"
Using require instead of include will return an error and halt the program execution if it cannot locate the requested file. This will help you if you misplaced a file or you got the file name wrong. But the story is the same, require will reload the file each time, the problems of this matter are the same as when using include command. The final and best solution is require_once command.

Using require_once

require_once "functions.php"
Like include_once this will only ever load in a single copy of the file, no matter how often that file is required. But, unlike include, it will also generate an error if it can not find the requested file.