autoloader

Posted in PHP by

PHP Autoloading allows you to speed up development, because you no longer include every file by hand. PHP offers different methods to enables autoloading, learn about the differences and keep the hints in mind.

function __autoload

If you define a function __autoload($classname), you have to take care of autoloading yourself. The function will be called each time you try to use a class that has not been defined yet. The variable $classname contains the classname without the extension. i.e.: "MyClass". Below is an example function.

<php
function __autoload($classname)
{
 $class = 'classes/'.$classname.'.php';
 include($class);
}

spl_autoload

The above "function __autoload" was a huge improvement, but you were only allowed to have one single autoload function, which is often enough, but once your project grows and you start using third party librarys which use their own autoloader...it is time for a more flexible solution.

PHP will call every callback function you registered with spl_autoload_register("functionname") in the order you added them.

If you call spl_autoload_register(); without any parameters the default native and very fast autoloader will be used.

PHP will lowercase your namespace and classname. Every namespace is convereted to a directory. i.e.: \Hello\World would include hello/world.php.

PHP classes and method names are case insensitive.

Tips and Hints

  • Autoloading does not work in console mode (CLI)
  • you can define the default include path with set_include_path('foldername');
  • you can define the default extension with spl_autoload_extensions(".php");
  • you can convert _ to / with strtr very fast (in case you use _ in your classnames)

Published at , Updated at 2011-11-14

prev: Strings Heredoc Nowdoc