PHP autoloader, require and include explained
Using include, require
Traditionally, PHP uses
require(‘script.name’) whenever you want to include the external PHP script. If you have problems with relative versus absolute paths, or you want to share scripts between different codebases, you have a further option to add
include_path="/var/lib/myphp/includes" in php.ini file to include well know places where PHP engine will look for files. You can then just use simple format include(‘myfile.php’) instead of full path.
Include and require are identical, except upon failure:
- require will produce a fatal error (E_COMPILE_ERROR) and stop the script
- include will only produce a warning (E_WARNING) and the script will continue
Using this aproach, your code is full of this include / require directives and looks like this:
<?php include("../include/session.php"); include("../include/databse.php"); ?>
If you use PHP classes, you must pay additional attention not to include or require the same script with same class twice. To avoid this, you can use include_once, require_once directive, which will load source only if it was not already loaded.
Using PHP Autoloader
From PHP 5.X on, you can take advantage of autoloader. Autoloader will try to load unknown PHP class when encountered. How this works? In your main entry point (bootstrap script or class) you register a function as a autoloader implementation. Inside function you must instructs PHP engine, from where to load script that contains given class. Together with PHP namespaces, you can make a really simple autoloader function implementation, that will significantly reduce your class names and took advantage of convention over configuration.
Summary of all options for including external PHP scripts
|include, require||old way; include script with functions; included file can be a symlink; If script contains classes it will throw a “class already defined error”, if you have it included twice.|
|require_once, include_once||only suitable method if PHP file script contains classes; will not throw error if included once ...|
For demonstration of autoloader please see my Github : https://github.com/gustinmi/php2e/blob/master/Bootstrap.php