Back to blog
PHPJanuary 30, 2011

Autoloading Classes in PHP with __autoload()

Eliminating repetitive include statements in PHP by leveraging the __autoload() function for automatic class loading.


In PHP, class imports do not follow the conventional import package.class paradigm found in languages like Java. Instead, developers must explicitly include each class file, which quickly becomes unwieldy in larger codebases.


The __autoload() function provides an elegant solution. When you instantiate a class with new ClassName() and that class has not yet been loaded, PHP automatically invokes __autoload(), giving you the opportunity to include the appropriate file dynamically.


Implementation


function __autoload($class_name) {

include $class_name . '.php';

}


$obj = new MyClass(); // MyClass.php is included automatically


This approach is especially valuable in large projects with dozens or hundreds of class files. Rather than maintaining a growing list of include statements at the top of every file, the autoloader resolves dependencies on demand.


Modern Best Practice


As of PHP 5.1, the recommended approach is spl_autoload_register(), which supports multiple autoloaders and integrates seamlessly with frameworks and Composer. If you are working on a modern PHP project, this should be your default choice.