How To: PHP Autoloading classes with multi platform namespace support

by Niki on January 5, 2012

While doing some research about the autoloading features in PHP it soon became clear that the build in support aka a non parameterized call to spl_autoload_register(); had little to offer. What this call does is tell PHP that we want to use the build in spl_autoload function for autoloading. While this is nice in theory, in practice this default implementation falls way to short.

What bothered me the most was the lack of build in support for namespaces. The kind of support where a namespace represents the folder where the class file can be found.

Luckily PHP gives us a way to define our own autoload function which will be called upon instantiating an object from an unknown class. So I wrote a simple implementation for a fully functional autoloader with support for namespaces on both Linux and Windows.

function autoload_class ( $namespace_class ){

  // Adapt to OS. Windows uses '\' as directory separator, linux uses '/'
  $path_file = str_replace( '\\', DIRECTORY_SEPARATOR, $namespace_class );

  // Get the autoload extentions in an array
  $autoload_extensions = explode( ',', spl_autoload_extensions() );

  // Loop over the extensions and load accordingly
  foreach( $autoload_extensions as $autoload_extension ){
      include_once( $path_file . $autoload_extension );


// Setting the path (I use linux) so our includes work.
set_include_path( get_include_path() . PATH_SEPARATOR . './' );

// Only try to autoload files with this extension(s)
spl_autoload_extensions( '.php' );

// Register our autoload_class function as the spl_autoload implementation to use
spl_autoload_register( 'autoload_class' );

Now if we try to instantiate an object of which the class file is not yet loaded, PHP will call our autoload function and automagically load our class file.

// Instantiating SomeObject from the class NamespaceName\SomeClass located in the file NamespaceName/SomeClass.php
$SomeOject = new NamespaceName\SomeClass();


{ 1 comment… read it below or add one }

Bhumi February 20, 2015 at 12:45 pm

Great help, Thanks for sharing this.


Cancel reply

Leave a Comment

Previous post:

Next post: