PHP autoloader, require and include explained

PHP autoloader, require and include explained

Autoloader works only for classes nad namespaces. You cannot use it for normal files with functions.

Using include, require

Traditionally, PHP uses include(‘script.name’) or 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.

For demonstration of autoloader please see my Github : https://github.com/gustinmi/php2e/blob/master/Bootstrap.php